//
//  LiveRoomViewController.m
//  YouinRTCDemo
//
//  Created by super on 2021/10/31.
//

#import "LiveRoomViewController.h"
#import <WebKit/WebKit.h>
#import "LiveChatViewController.h"
#import "LiveUserInfoModel.h"
#import "LiveNoticeViewController.h"
#import "LiveGoodsViewController.h"
#import <TXScrollLabelView/TXScrollLabelView.h>
#import "AFNetworking.h"
#import "RYAlertController.h"
#import "ForbiddenView.h"
#import <LSTPopView.h>
#import "OnlinePeopleView.h"
#import "AppDelegate.h"
#import "PrivateModel.h"
#import <AVFoundation/AVFoundation.h>
#import "EnterTipView.h"
#import "PrivateChatView.h"
#import "OnlineModel.h"
#import "LandscapeViewController.h"
#import "BottomAlertActionView.h"
//声网
#import <AgoraRtcKit/AgoraRtcKit.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "Reachability.h"
//#import "BeautyView.h"
#import "AdaptiveBackgroundView.h"
#import "LiveStreamDataViewController.h"

//清晰度view
#import "ClarityBottomView.h"

///直播数据
#import "LiveStreamingData.h"
#import "FaceBeautyBottomView.h"
/** faceU */
#import "FUDemoManager.h"
// 流状态 String
static NSString *StreamState[] = {
    @"PLStreamStateUnknow",
    @"PLStreamStateConnecting",
    @"PLStreamStateConnected",
    @"PLStreamStateDisconnecting",
    @"PLStreamStateDisconnected",
    @"PLStreamStateAutoReconnecting",
    @"PLStreamStateError"
};
@interface LiveRoomViewController ()<YouinRTCDelegate,youinRTCChatDelegate,WKScriptMessageHandler,WKNavigationDelegate,UITextViewDelegate,RTCChatVCDelegate,ClearAllRedPointDelegate,AgoraRtcEngineDelegate,BottomActionsDelegate,AgoraVideoFrameDelegate,ClarityButtonsDelegate>//,BeatutyDelegate
@property(nonatomic,strong)YouinRTCManager *manager;
@property(nonatomic,strong)NSMutableDictionary *makeupDict;

/// UI
@property(nonatomic,strong)UIImageView *avatar;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UILabel *watchLabel;
@property(nonatomic,strong)UIView *avatarBgView;
@property(nonatomic,strong)UIButton *noticeButton;
@property(nonatomic,strong)UIButton *backButton;
@property(nonatomic,strong)UIButton *cameraButton;
@property(nonatomic,strong)UIButton *mirrorButton;///镜像
@property(nonatomic,strong)UIButton *microButton;
@property(nonatomic,strong)UIButton *beautyButton;
@property(nonatomic,strong)UIButton *videoRatioButton;
@property(nonatomic,strong)UIButton *ticketButton;
@property(nonatomic,strong)UIButton *loveButton;
@property(nonatomic,strong)UILabel *loveLabel;
@property(nonatomic,strong)UIButton *linkButton;
@property(nonatomic,strong)UIButton *messageButton;
@property(nonatomic,strong)UIButton *bagButton;
@property(nonatomic,strong)UIButton *beginButton;
@property(nonatomic,strong)UIButton *closeButton;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)UILabel *beginTimeLabel;
@property(nonatomic,strong)UIView *beginView;
@property(nonatomic,strong)UILabel *timeCountLabel;
@property(nonatomic,strong)UIView *networkView;//网络质量背景view
@property(nonatomic,strong)UIImageView *networkImg;//信号图片
@property(nonatomic,strong)UIButton *bitrateBtn;//显示码率
@property(nonatomic,strong)NSMutableArray *buttonTitleArray;
@property(nonatomic,strong)NSArray *tracksArray;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSTimer *roomStateTimer;
@property(nonatomic,assign)int seconds;
@property(nonatomic,assign)int roomStateSeconds;
@property(nonatomic,assign)bool isLive;
@property(nonatomic,strong)LiveChatViewController *chatTable;
@property(nonatomic,strong)UIView *ratioView;
@property(nonatomic,strong)UIView *chatInputView;
@property(nonatomic,strong)UITextView *chatTextView;
@property(nonatomic,strong)UIButton *sendbutton;
@property(nonatomic,strong)LiveUserInfoModel *liveUserInfoModel;
@property(nonatomic,assign)long timeCount;
@property(nonatomic,strong)LiveNoticeViewController *noticeVC;
@property(nonatomic,strong)LiveGoodsViewController *liveGoodsVC;
@property(nonatomic,strong)CourseModel *corseInfoModel;
@property(nonatomic,strong)NSString *currentURL;
@property(nonatomic,strong)NSTimer *publishTimer;
@property(nonatomic,assign)bool isPublishLocal;
@property(nonatomic,assign)int retryCount;
@property(nonatomic,strong)UIButton *back;
@property(nonatomic,strong)UIView *tapView;
@property(nonatomic,strong)TXScrollLabelView *horScrollView;
@property(nonatomic,assign)bool isMuteAll;//禁言所有人
@property(nonatomic,strong)StatusModel *dataModel;
@property(nonatomic,strong)UIButton *forbiddenBtn;//禁言，拉黑列表
@property(nonatomic,strong)UIButton *onlineBtn;//在线人数
@property(nonatomic,strong)UILabel *redPoint;//有红点
@property(nonatomic,strong)PrivateModel *privateModel;

@property (nonatomic, strong) AVAudioPlayer *player;
//判断是否断网重连
@property (nonatomic, assign)BOOL isRoomStateConnected;
@property(nonatomic,strong)NSMutableArray *enterTimeArray;
@property(nonatomic,strong)NSMutableArray *enterNameArray;
@property(nonatomic,strong)NSMutableArray *enterTipViews;
@property(nonatomic,strong)NSTimer *enterTimer;
@property (strong, nonatomic) NSTimer *__nullable heatBeat;
@property (assign, nonatomic) NSTimeInterval reConnectTime;
//在线观众背景view
@property (strong, nonatomic) AdaptiveBackgroundView *onlinePeopleView;
//@property (strong, nonatomic)UILabel *onlineLabel;//在线观众
@property(nonatomic,strong)NSTimer *onlineTimer;//在线观众刷新
@property(nonatomic,assign)int onLineSeconds;//在线刷新秒
@property(nonatomic,strong)UIView *headImgView;
@property(nonatomic,strong)UIButton *peopleBtn;//在线人数


// 定义 agoraKit 变量
@property (nonatomic, strong)AgoraRtcEngineKit *agoraKit;
@property (nonatomic, strong)AgoraBeautyOptions *baseBeautifyOption;//基础美颜
//@property (nonatomic, strong)AgoraFaceShapeBeautyOptions *beautyOptions;//进阶美颜
// 定义 localView 变量
@property (nonatomic, strong) UIView *localView;
@property (nonatomic, assign)BOOL isAgoraRtcBegin;//是否已开始直播 对声网
@property(nonatomic,assign)int offLoneSeconds;//判断掉线超过10秒后，重连链接
@property(nonatomic,strong)NSTimer *__nullable countTimer;
///重连次数
//@property(nonatomic,assign)int connectedCount;
@property (nonatomic, assign)NSInteger videoBitrate;
@property (nonatomic, assign)BOOL isOpenBeauty;//是否打开美颜

//@property (nonatomic, assign) NSInteger browStyleInt;
//@property(nonatomic, assign) float browStrength;
//
//@property (nonatomic, assign) NSInteger lashStyleInt;
//@property(nonatomic, assign) float lashStrength;
//
//@property (nonatomic, assign) NSInteger shadowStyleInt;
//@property(nonatomic, assign) float shadowStrength;
//
//@property (nonatomic, assign) NSInteger pupilStyleInt;
//@property(nonatomic, assign) float pupilStrength;
//
//@property (nonatomic, assign) NSInteger blushStyleInt;
//@property (nonatomic, assign) NSInteger blushColor;
//@property(nonatomic, assign) float blushStrength;
//
//@property (nonatomic, assign) NSInteger lipStyleInt;
//@property (nonatomic, assign) NSInteger lipColor;
//@property(nonatomic, assign) float lipStrength;
//@property (nonatomic, assign) NSInteger browColor;
//@property (nonatomic, assign) NSInteger lashColor;

@property (nonatomic, strong) FUDemoManager *demoManager;
@property (nonatomic, strong) UIButton *skipButton;
@property (nonatomic, assign) BOOL isFrontCamera;
///是否第一次开始直播
@property (nonatomic, assign) BOOL isFirstTimeLive;

@property (nonatomic, strong) FaceBeautyBottomView *faceBeautyView;
@property (nonatomic, assign) CGSize agoraRtcSize;
@end

@implementation LiveRoomViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.isAgoraRtcBeauty) {
        [[FUDemoManager shared] saveBeauty];
    }
    
//    if(self.isAgoraRtc){
//        [self leaveChannel];
//    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.videoBitrate = 2200;
    self.agoraRtcSize = CGSizeMake(720, 1280);
    self.isAgoraRtcBegin = NO;
    self.isRoomStateConnected = NO;
    self.isFirstTimeLive = YES;
    
    self.roomStateSeconds = 30;
    self.offLoneSeconds = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    self.enterTimeArray = [NSMutableArray array];
    self.enterNameArray = [NSMutableArray array];
    self.enterTipViews = [NSMutableArray array];
    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
    self.tracksArray = [NSArray new];
    self.buttonTitleArray = [NSMutableArray arrayWithArray:@[@"高清",@"超清",@"高清",@"标清",@"流畅"]];
    // 将用户在有因后台进行绑定
    [self initEngine];
    [self setUI];
    
    
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"msg" ofType:@"mp3"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    self.retryCount = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [self.navigationController setNavigationBarHidden:true animated:true];
    
    self.isMuteAll = NO;
}


-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.manager leaveRoom];
    
}

-(void)setUI{
    
    self.avatarBgView = [UIView new];
    self.avatarBgView.backgroundColor = rgba(0, 0, 0, 0.4);
    self.avatarBgView.layer.cornerRadius = 22.5;
    self.avatarBgView.layer.masksToBounds = YES;
    [self.view addSubview:self.avatarBgView];
    
    self.titleLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:12] textColor:[UIColor whiteColor]];
    self.titleLabel.text = @"";
    [self.avatarBgView addSubview:self.titleLabel];
    
    self.watchLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:10] textColor:[UIColor whiteColor]];
    self.watchLabel.text = @"";
    [self.avatarBgView addSubview:self.watchLabel];
    
    self.avatar = [UIImageView new];
    self.avatar.layer.cornerRadius = 16.5;
    self.avatar.layer.masksToBounds = YES;
    self.avatar.backgroundColor = [UIColor clearColor];
    [self.avatarBgView addSubview:self.avatar];
    
    self.noticeButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"pen"] title:@"公告：" font:[UIFont systemFontOfSize:10] backColot:rgba(255, 153, 0, 1) textColor:[UIColor whiteColor] target:self action:@selector(noticeAction) layer:10.5];
    [self.view addSubview:self.noticeButton];
    
    self.horScrollView = [TXScrollLabelView scrollWithTitle:@"" type:TXScrollLabelViewTypeLeftRight velocity:1 options:UIViewAnimationOptionTransitionFlipFromTop];
    self.horScrollView.backgroundColor = [UIColor clearColor];
    self.horScrollView.scrollTitleColor = [UIColor whiteColor];
    self.horScrollView.font = [UIFont systemFontOfSize:12];
    self.horScrollView.userInteractionEnabled = false;
    [self.view addSubview:self.horScrollView];
    
    //返回按钮
    self.backButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"back"] title:@"" font:nil backColot:[UIColor clearColor] textColor:nil target:self action:@selector(backAction) layer:0];
    [self.view addSubview:self.backButton];
    
    
    
    
//    self.onlineLabel = [[UILabel alloc] init];
//    self.onlineLabel.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
//    self.onlineLabel.text = @"暂无在线观众";
//    self.onlineLabel.textColor = [UIColor whiteColor];
//    self.onlineLabel.textAlignment = 1;
//    self.onlineLabel.backgroundColor = rgba(0, 0, 0, 0.4);
//    self.onlineLabel.layer.cornerRadius = 15;
//    self.onlineLabel.clipsToBounds = YES;
//    self.onlineLabel.hidden = NO;
//    [self.view addSubview:self.onlineLabel];
    self.onlinePeopleView = [[AdaptiveBackgroundView alloc] init];
    [self.view addSubview:self.onlinePeopleView];
    
    
    self.peopleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.peopleBtn.layer.cornerRadius = 15;
    self.peopleBtn.clipsToBounds = YES;
    self.peopleBtn.backgroundColor = rgba(0, 0, 0, 0.4);
    [self.peopleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.peopleBtn.titleLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
    [self.peopleBtn addTarget:self action:@selector(onlineBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.peopleBtn];
    self.peopleBtn.hidden = YES;
    
    
    self.cameraButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"camera"] title:@"" font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(cameraAction) layer:20];
    [self.view addSubview:self.cameraButton];
    
    self.mirrorButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"mirror2"] title:@"" font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(mirrorAction:) layer:20];
    [self.view addSubview:self.mirrorButton];
    
    NSInteger mirrorIndex = [Tool safeIntForKey:@"Mirror-direction" defaultValue:1];
    [self.agoraKit setLocalRenderMode:AgoraVideoRenderModeHidden mirror:mirrorIndex];
    self.mirrorButton.selected = mirrorIndex==2?YES:NO;
    [self.mirrorButton setImage:[UIImage imageNamed:self.mirrorButton.selected?@"mirror1":@"mirror2"] forState:UIControlStateNormal];
    
    
    self.microButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"mic2"] title:@"" font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(micAction:) layer:20];
    [self.view addSubview:self.microButton];
    
    self.beautyButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"beauty2"] title:@"" font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(beautyAction:) layer:20];
    self.beautyButton.selected = YES;
    [self.view addSubview:self.beautyButton];
    
    self.forbiddenBtn = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"setting"] title:nil font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(forbiddenBtnAction) layer:20];
    [self.view addSubview:self.forbiddenBtn];
    
    
   self.onlineBtn = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"people_img"] title:nil font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(onlineBtnAction) layer:20];
   [self.view addSubview:self.onlineBtn];
    
    self.redPoint = [[UILabel alloc] init];
    self.redPoint.backgroundColor = [UIColor redColor];
    self.redPoint.layer.cornerRadius = 5;
    self.redPoint.clipsToBounds = YES;
    [self.view addSubview:self.redPoint];
    self.redPoint.hidden = YES;
    
    NSInteger segmentIndex = [Tool safeIntForKey:@"agoraRtcSizeWith" defaultValue:self.version_id==18?720:540];
    NSInteger videoBitrateValue = [Tool safeIntForKey:@"videoBitrate" defaultValue:self.version_id==18?2200:1200];
    self.videoBitrate = videoBitrateValue;
    
    NSString *title = @"高清";
    if (segmentIndex == 1080) {
        title = @"超清";
    }else if(segmentIndex == 720)
    {
        title = @"高清";
    }else if(segmentIndex == 540)
    {
        title = @"标清";
    }else if(segmentIndex == 360){
        title = @"流畅";
    }
    
    self.videoRatioButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:nil title:title font:[UIFont systemFontOfSize:14] backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(videoRationAction) layer:20];
    [self.view addSubview:self.videoRatioButton];
    
    //优惠券
    self.ticketButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"ticket"] title:@"" font:nil backColot:[UIColor clearColor] textColor:nil target:self action:@selector(ticketAction) layer:20];
    [self.ticketButton setHidden:true];
    [self.view addSubview:self.ticketButton];
    
    //点赞
    self.loveButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"love"] title:@"" font:nil backColot:[UIColor clearColor] textColor:nil target:self action:@selector(loveAction) layer:0];
    [self.view addSubview:self.loveButton];
    
    self.loveLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:10] textColor:[UIColor whiteColor]];
    self.loveLabel.backgroundColor = rgba(0, 0, 0, 0.4);
    self.loveLabel.textAlignment = NSTextAlignmentCenter;
    self.loveLabel.text = @"";
    self.loveLabel.layer.cornerRadius = 6;
    self.loveLabel.layer.masksToBounds = YES;
    [self.loveButton addSubview:self.loveLabel];
    [self.loveButton setHidden:true];
    
    //链接
    self.linkButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"link"] title:@"" font:nil backColot:[UIColor clearColor] textColor:nil target:self action:@selector(linkAction) layer:20];
    [self.view addSubview:self.linkButton];
    [self.linkButton setHidden:true];
    
    //发消息图片
    self.messageButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"comment"] title:@"" font:nil backColot:rgba(0, 0, 0, 0.4) textColor:nil target:self action:@selector(messageAction) layer:20];
    [self.view addSubview:self.messageButton];
    
    //购物车
    self.bagButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bagButton setBackgroundImage:[UIImage imageNamed:@"bag"] forState:UIControlStateNormal];
//    [self.bagButton setTitle:self.product_count forState:UIControlStateNormal];
    self.bagButton.titleLabel.font = [UIFont systemFontOfSize:10 weight:UIFontWeightMedium];
    [self.bagButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.bagButton addTarget:self action:@selector(bagAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.beginButton.userInteractionEnabled = false;
    [self.view addSubview:self.bagButton];
    
    // 关闭直播
    self.closeButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:[UIImage imageNamed:@"close"] title:@"" font:nil backColot:[UIColor clearColor] textColor:nil target:self action:@selector(closeAction) layer:0];
    self.closeButton.hidden = true;
    [self.view addSubview:self.closeButton];
    
    
    self.beginView = [UIView new];
    self.beginView.backgroundColor = rgba(0, 255, 42, 1);
    self.beginView.hidden = true;
    self.beginView.layer.cornerRadius = 5;
    self.beginView.layer.masksToBounds = YES;
    [self.view addSubview:self.beginView];
    
    self.beginTimeLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:10] textColor:[UIColor whiteColor]];
    self.beginTimeLabel.text = @"";
    self.beginTimeLabel.hidden = true;
    [self.view addSubview:self.beginTimeLabel];
    
    
    self.networkView = [[UIView alloc] init];
    [self.view addSubview:self.networkView];
    self.networkView.hidden = YES;
    self.networkImg = [[UIImageView alloc] init];
    self.networkImg.image = [UIImage imageNamed:@"qualityDetecting"];
    [self.networkView addSubview:self.networkImg];
    
    // 创建按钮
    self.bitrateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    // 设置按钮标题
//    [self.bitrateBtn setTitle:@"码率：1900kbps" forState:UIControlStateNormal];
    [self.bitrateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.bitrateBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    self.bitrateBtn.contentEdgeInsets = UIEdgeInsetsMake(2, 8, 2, 8);
    self.bitrateBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.bitrateBtn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
    self.bitrateBtn.layer.cornerRadius = 10;
    self.bitrateBtn.clipsToBounds = YES;
    // 添加到父视图
    [self.networkView addSubview:self.bitrateBtn];

    
    
    //开始直播
    self.beginButton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectZero image:nil title:@"开始直播" font:[UIFont systemFontOfSize:18] backColot:rgba(25, 148, 255, 1) textColor:[UIColor whiteColor] target:self action:@selector(beginAction:) layer:22.5];
    [self.view addSubview:self.beginButton];
    
    //直播开始倒计时
    self.timeLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"直播倒计时" font:[UIFont systemFontOfSize:21] textColor:[UIColor whiteColor]];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.hidden = true;
    [self.view addSubview:self.timeLabel];
    
    self.timeCountLabel = [[UIFactory shareInstace] setLabel:CGRectZero text:@"" font:[UIFont systemFontOfSize:21] textColor:[UIColor whiteColor]];
    self.timeCountLabel.textAlignment = NSTextAlignmentCenter;
    self.timeCountLabel.hidden = true;
    [self.view addSubview:self.timeCountLabel];
    
    self.ratioView = [UIView new];
    self.ratioView.backgroundColor = rgba(0, 0, 0, 1.0);
    self.ratioView.layer.cornerRadius = 20;
    self.ratioView.layer.masksToBounds = YES;
    self.ratioView.hidden = true;
    [self.view addSubview:self.ratioView];
    
    // 聊天
    self.chatTable = [LiveChatViewController new];
    self.chatTable.vcdelegate = self;
    [self addChildViewController:self.chatTable];
//    self.chatTable.view.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.chatTable.view];
    [self.chatTable didMoveToParentViewController:self];
    self.chatInputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.chatInputView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.chatInputView addGestureRecognizer:tap];
    self.chatInputView.hidden = true;
    [self.view addSubview:self.chatInputView];
    
    
    

    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-70, SCREEN_WIDTH, 150)];
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    view.backgroundColor = rgba(245, 246, 250, 1);
    [self.chatInputView addSubview:view];
    
    self.chatTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, SCREEN_HEIGHT-50,SCREEN_WIDTH-5-70-5 , 28)];
    self.chatTextView.font = [UIFont systemFontOfSize:14];
    self.chatTextView.delegate = self;
    [self.chatInputView addSubview:self.chatTextView];
    
    self.sendbutton = [[UIFactory shareInstace] setButton:UIButtonTypeCustom frame:CGRectMake(SCREEN_WIDTH-70, SCREEN_HEIGHT-50, 55, 28) image:nil title:@"发送" font:[UIFont systemFontOfSize:13] backColot:rgba(25, 148, 255, 1) textColor:[UIColor whiteColor] target:self action:@selector(sendMessage) layer:3];
    [self.chatInputView addSubview:self.sendbutton];
    
    
    //视频清晰度
    for(int i = 0;i<self.buttonTitleArray.count;i++){
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        int sum = 0;
        int flag = 0;
        if(i <= 1){
            sum = 0;
        }else{
            sum = i-1;
        }
        if(i < 1){
            flag = 0;
        }else{
            flag = 1;
        }
        
        if(i == 0){
            button.frame = CGRectMake(0, 0, 40, 40);
        }else{
            button.frame = CGRectMake(0, 13.5+ flag*24 + 15*i + 15*sum, 40, 15);
        }
        
        button.tag = 100+i;
        [button addTarget:self action:@selector(changeRatioAction:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:self.buttonTitleArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:rgba(25, 148, 255, 1) forState:UIControlStateSelected];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.ratioView addSubview:button];
    }
    self.tapView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-80, SCREEN_HEIGHT)];
    UITapGestureRecognizer *rotaTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ratioTapAction)];
    [self.tapView addGestureRecognizer:rotaTap];
    self.tapView.userInteractionEnabled = false;
    [self.view addSubview:self.tapView];
    
    [self updateOnlinePeople];
    
    [self layout];
    
    //默认是30秒刷新一次
    self.onLineSeconds = 10;

    
}


- (void)updateOnlinePeople{
    self.headImgView = [[UIView alloc] init];
    [self.view addSubview:self.headImgView];
    self.headImgView.hidden = YES;
}


-(void)layout{
    [self.avatarBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight+20);
        make.left.mas_equalTo(self.view).offset(15);
        make.height.mas_equalTo(45);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH-100);
        
    }];
    
    [self.peopleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view).offset(-20);
        make.top.mas_equalTo(self.avatarBgView);
        make.width.height.offset(30);
    }];
    
    [self.headImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.peopleBtn.mas_left).offset(-1);
        make.top.mas_equalTo(self.peopleBtn);
        make.height.offset(30);
        make.width.offset(150);
    }];
    
    
    [self.avatar mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.avatarBgView).offset(6);
        make.left.mas_equalTo(self.avatarBgView).offset(6);
        make.height.width.mas_equalTo(33);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.avatarBgView).offset(10);
        make.left.mas_equalTo(self.avatar.mas_right).offset(5);
        make.right.mas_equalTo(self.avatarBgView).offset(-22);
        make.height.mas_equalTo(11);
        
    }];
    
    [self.watchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.titleLabel);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(4.5);
        make.right.mas_equalTo(self.avatarBgView).offset(-22);
        make.height.mas_equalTo(10);
    }];
    
    [self.noticeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(15);
        make.top.mas_equalTo(self.avatarBgView.mas_bottom).offset(10);
        make.height.mas_equalTo(21);
        make.width.mas_equalTo(64);
    }];
    
    [self.beginView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(self.avatarBgView.mas_left).offset(10);
        make.left.mas_equalTo(self.view).offset(15);
        make.width.height.mas_equalTo(10);
        make.top.mas_equalTo(self.noticeButton.mas_bottom).offset(10);
    }];
    
    [self.beginTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.beginView.mas_right).offset(5.5);
        make.height.mas_equalTo(10);
        make.centerY.mas_equalTo(self.beginView);
    }];
    
    [self.networkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.beginTimeLabel.mas_right).offset(10);
        make.centerY.mas_equalTo(self.beginTimeLabel);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    
    [self.networkImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 20));
        make.left.centerY.mas_equalTo(self.networkView);
    }];
    
    [self.bitrateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.networkImg.mas_right).offset(5);
        make.centerY.mas_equalTo(self.networkView);
        make.height.offset(20);
    }];
    
    [self.horScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(15);
        make.top.mas_equalTo(self.avatarBgView.mas_bottom).offset(10);
        make.height.mas_equalTo(21);
        make.width.mas_equalTo(100);
    }];
    
    [self.onlinePeopleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.avatarBgView);
        make.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.onlinePeopleView.mas_bottom).offset(20);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.cameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backButton.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.mirrorButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.cameraButton.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.microButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.mirrorButton.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.beautyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.microButton.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.videoRatioButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.beautyButton.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    [self.forbiddenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.videoRatioButton.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.onlineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.forbiddenBtn.mas_bottom).offset(15);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.redPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(10);
        make.left.mas_equalTo(self.onlineBtn.mas_right).offset(-10);
        make.bottom.mas_equalTo(self.onlineBtn.mas_top).offset(10);
    }];
    
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.onlineBtn.mas_bottom).offset(15);
        make.width.height.mas_equalTo(45);
        make.right.mas_equalTo(self.view).offset(-12.5);
    }];
    
    [self.bagButton mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-17.5);
        } else {
            // Fallback on earlier versions
        }
        make.width.height.mas_equalTo(44.5);
        make.left.mas_equalTo(self.view).offset(13);
    }];
    
    [self.beginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.bagButton);
        make.left.mas_equalTo(self.bagButton.mas_right).offset(17.5);
        make.right.mas_equalTo(self.messageButton.mas_left).offset(-20);
        make.height.mas_equalTo(45);
    }];
    
    [self.messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.bagButton);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.linkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.messageButton.mas_top).offset(-15.5);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.loveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.linkButton.mas_top).offset(-15.5);
        make.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.loveLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.loveButton);
        make.height.mas_equalTo(12);
        make.left.mas_equalTo(self.loveButton).offset(4);
        make.right.mas_equalTo(self.loveButton).offset(-4);
    }];
    
    [self.ticketButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.loveButton.mas_top).offset(-15.5);
        make.width.height.mas_equalTo(40);
        make.right.mas_equalTo(self.view).offset(-15);
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view).offset(-80);
        make.height.mas_equalTo(20);
    }];
    
    [self.timeCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.timeLabel.mas_bottom).offset(14.5);
        make.height.mas_equalTo(20);
    }];
    
    [self.chatTable.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-75);
        } else {
            // Fallback on earlier versions
        }
        make.right.mas_equalTo(self.view).offset(-100);
        make.height.mas_equalTo(270);
    }];
    
    
    [self.view layoutIfNeeded];
    [self.noticeButton layoutButtonWithEdgeInsetsStyle:GLButtonEdgeInsetsStyleRight imageTitleSpace:2.5];
}


-(void)sendMessage{
    if([self.chatTextView.text isEqualToString:@""]){
        [[ZXMessageCase shareInstace] showMessage:@"不能发送空消息"];
        return;
    }
    [self.manager sendTextMessage:self.chatTextView.text callback:nil];
    self.chatTextView.text = @"";
    [self.chatTextView resignFirstResponder];
}

-(void)noticeAction{
    
    self.noticeVC = [LiveNoticeViewController new];
    self.noticeVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self addChildViewController:self.noticeVC];
    [self.view addSubview:self.noticeVC.view];
    [self.noticeVC didMoveToParentViewController:self];
    [self.noticeVC show];
    __weak typeof(self) weakSelf = self;
    self.noticeVC.block = ^(NSString * _Nonnull str) {
        weakSelf.horScrollView.scrollTitle = str;
        [weakSelf.noticeButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(120);
        }];
        [weakSelf.horScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(120);
        }];
        [weakSelf.view layoutIfNeeded];
        [weakSelf.horScrollView beginScrolling];
        [weakSelf.noticeButton setImage:nil forState:UIControlStateNormal];
        [weakSelf.noticeButton setTitle:@"" forState:UIControlStateNormal];
    };
    
   
   
}

-(void)backAction{
    if(self.isLive){
        // 初始化对话框
        __weak typeof(self) weakSelf = self;
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认离开直播间" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                [weakSelf quitRoom:NO];
            }];
            UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

            [alert addAction:okAction];
            [alert addAction:cancelAction];

            // 弹出对话框
            [self presentViewController:alert animated:true completion:nil];
    }else{
        [self.chatTable.view setHidden:true];
        [self.manager leaveRoom];
        [self.timer invalidate];
        self.timer = nil;
        if(self.isAgoraRtc){
            [self leaveChannel];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    //销毁聊天室
    [PrivateChatView clearSharedView];
}

-(void)cameraAction{
    if(self.isAgoraRtc){
        _isFrontCamera = !_isFrontCamera;
        [self.agoraKit switchCamera];
        [FUDemoManager resetTrackedResult];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:_isFrontCamera forKey:@"camera-direction"];
        [defaults synchronize];
    }else{
        [self.manager changeCamera];
    }
    
   
}

///镜像
- (void)mirrorAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if(self.isAgoraRtc){
        
        ///设置本地镜像
        [self.agoraKit setLocalRenderMode:AgoraVideoRenderModeHidden mirror:sender.selected?AgoraVideoMirrorModeDisabled:AgoraVideoMirrorModeEnabled];
        CGSize size = CGSizeZero;
        NSInteger bitrate = 0;
        NSInteger minBitrate = 0;
        if (self.videoBitrate == 3000) {
            ///超清
            size = CGSizeMake(1080, 1920);
            bitrate = 3000;
            minBitrate = 800;
        }
       else if(self.videoBitrate == 2200){
            ///高清
            size = CGSizeMake(720, 1280);
            bitrate = 2200;
            minBitrate = 800;
        }else if (self.videoBitrate == 1200){
            
            size = CGSizeMake(540, 960);
            bitrate = 1200;
            minBitrate = 800;
            
        }else if (self.videoBitrate == 800){
            size = CGSizeMake(360, 640);
            bitrate = 800;
            minBitrate = 600;
        }else{
            ///高清
            size = CGSizeMake(720, 1280);
            bitrate = 2200;
            minBitrate = 800;
        }
        ///设置远端镜像
        AgoraVideoEncoderConfiguration *encoderConfig = [[AgoraVideoEncoderConfiguration alloc] initWithSize:size frameRate:(AgoraVideoFrameRateFps24) bitrate:bitrate orientationMode:(AgoraVideoOutputOrientationModeFixedPortrait)mirrorMode:(sender.selected?AgoraVideoMirrorModeDisabled:AgoraVideoMirrorModeEnabled)];
        encoderConfig.codecType = AgoraVideoCodecTypeH264;
        encoderConfig.degradationPreference = AgoraDegradationMaintainResolution;
        encoderConfig.minBitrate = minBitrate;//最小码率
        [self.agoraKit setVideoEncoderConfiguration:encoderConfig];
    }else{
        if(self.isLive){
            [[ZXMessageCase shareInstace] showMessage:@"直播中不能切换镜像"];
            return;
        }
        [self.manager switchMirror:!sender.selected isLive:self.isLive];
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:sender.selected?2:1 forKey:@"Mirror-direction"];
    [defaults synchronize];
    
    [self.mirrorButton setImage:[UIImage imageNamed:sender.selected?@"mirror1":@"mirror2"] forState:UIControlStateNormal];
}

-(void)micAction:(UIButton *)sender{
    
    if(self.isAgoraRtc){
        sender.selected = !sender.selected;
        if(sender.selected){
            [self.agoraKit disableAudio];//关闭音频模块。
            [[ZXMessageCase shareInstace] showMessage:@"关闭麦克风"];
        }else{
            [self.agoraKit enableAudio];// 启用音频模块。
            [[ZXMessageCase shareInstace] showMessage:@"打开麦克风"];
        }
        [self.microButton setImage:[UIImage imageNamed:sender.selected?@"mic1":@"mic2"] forState:UIControlStateNormal];
    }else{
        if(self.microButton.alpha == 1){
            [self.manager muteMicrophone:YES];
            self.microButton.alpha = 0.3;
            [[ZXMessageCase shareInstace] showMessage:@"关闭麦克风"];
        }else{
            [self.manager muteMicrophone:NO];
            self.microButton.alpha = 1;
            [[ZXMessageCase shareInstace] showMessage:@"打开麦克风"];
        }
    }
}

-(void)beautyAction:(UIButton *)sender{
    
    if(self.isAgoraRtc){
        sender.selected = !sender.selected;
        if (self.isAgoraRtcBeauty) {
            
//            if (sender.selected) {
//                [self.faceBeautyView hideView];
//            }else{
                
                [self.faceBeautyView showView];
//            }
            
//            BeautyView *beautyView = [[BeautyView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190)];
//            beautyView.delegate = self;
//            [beautyView showView];
//            __weak typeof(beautyView) weakBeautyView = beautyView; // 创建弱引用
//            beautyView.makeUpHeightBlock = ^(BOOL isHeight) {
//                if (isHeight == 1) {
//                    weakBeautyView.frame = CGRectMake(0, SCREEN_HEIGHT-240, SCREEN_WIDTH, 240);
//                }else{
//                    weakBeautyView.frame = CGRectMake(0, SCREEN_HEIGHT-190, SCREEN_WIDTH, 190);
//                }
//            };
        }else{
            [self.agoraKit setBeautyEffectOptions:sender.selected options:self.baseBeautifyOption];
            [self.beautyButton setImage:[UIImage imageNamed:sender.selected?@"beauty2":@"beauty1"] forState:UIControlStateNormal];
            [[ZXMessageCase shareInstace] showMessage:sender.selected?@"打开美颜":@"关闭美颜"];
            
        }
        
       
    }else{
        sender.selected = !sender.selected;
        [self.manager setBeautifyModeOn:sender.selected?YES:NO];
        [self.beautyButton setImage:[UIImage imageNamed:sender.selected?@"beauty2":@"beauty1"] forState:UIControlStateNormal];
        [[ZXMessageCase shareInstace] showMessage:sender.selected?@"打开美颜":@"关闭美颜"];
    }
}
//#pragma mark - 美颜，美妆 开关
//- (void)beautySwitchDelegate:(BOOL)isOn withTag:(NSInteger)tag
//{
//    
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    if (tag == 11) {
//        self.isOpenBeauty = isOn;
//        //基础美颜
////        [self.agoraKit setBeautyEffectOptions:isOn options:self.baseBeautifyOption];
//        [defaults setBool:isOn forKey:@"beautySwitchButton"];
//        //进阶美颜
////        [self.agoraKit setFaceShapeBeautyOptions:isOn options:self.beautyOptions];
//        
//    }else{
//        //美妆
//        [defaults setBool:isOn forKey:@"makeUpBeautySwitchButton"];
//        // 美妆开关
//        self.makeupDict[@"enable_mu"] = @(isOn);
//        [self makeUPBaseJsonData:self.makeupDict];
//    }
//    [defaults synchronize];
//}

#pragma mark - 美颜强度设置
//- (void)applyBeautyEffectsWithlightening:(float)lightening withRedness:(float)redness withSharpness:(float)sharpness withSmooth:(float)smooth
//{
//    if (self.isOpenBeauty) {
//        self.baseBeautifyOption.lighteningLevel = lightening;//亮度
//        self.baseBeautifyOption.rednessLevel = redness;//红润
//        self.baseBeautifyOption.sharpnessLevel = sharpness;//锐度
//        self.baseBeautifyOption.smoothnessLevel = smooth;//平滑
//        [self.agoraKit setBeautyEffectOptions:YES options:self.baseBeautifyOption];
////        [self.agoraKit setFaceShapeBeautyOptions:YES options:self.beautyOptions];
//
//        // 保存
//        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//        [defaults setFloat:lightening forKey:@"BeautifyLighteningLevel"];
//        [defaults setFloat:redness forKey:@"BeautifyRednessLevel"];
//        [defaults setFloat:sharpness forKey:@"BeautifySharpnessLevel"];
//        [defaults setFloat:smooth forKey:@"BeautifySmoothnessLevel"];
//        [defaults synchronize];
//    }
//    
//}

//- (void)makeUpSliders:(float)value withTag:(NSInteger)tag
//{
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    if (tag == 0) {
//        self.makeupDict[@"browStrength"] = @(value);
//        [defaults setInteger:value forKey:@"browStrength"];
//        
//    }else if (tag == 1)
//    {
//        self.makeupDict[@"lashStrength"] = @(value);
//        [defaults setInteger:value forKey:@"lashStrength"];
//    }else if (tag == 2)
//    {
//        self.makeupDict[@"shadowStrength"] = @(value);
//        [defaults setInteger:value forKey:@"shadowStrength"];
//    }else if (tag == 3)
//    {
//        self.makeupDict[@"pupilStrength"] = @(value);
//        [defaults setInteger:value forKey:@"pupilStrength"];
//    }else if (tag == 4)
//    {
//        self.makeupDict[@"blushStrength"] = @(value);
//        [defaults setInteger:value forKey:@"blushStrength"];
//    }else{
//        self.makeupDict[@"lipStrength"] = @(value);
//        [defaults setInteger:value forKey:@"lipStrength"];
//    }
//    [self makeUPBaseJsonData:self.makeupDict];
//    [defaults synchronize];
//}


//- (void)resetBeauty
//{
//    self.makeupDict = @{
//        @"enable_mu": @NO, // 美妆开关
//        @"browStyle":@(0),//眉毛类型 0 无, 1、2
//        @"browColor":@(1),//眉毛颜色 1 黑色，2，棕色
//        @"browStrength":@(1.0),//取值范围为 [0.0, 1.0]
//
//        @"lashStyle":@(0),//眼睫毛 0 无, 1、2
//        @"lashColor":@(1),//眼睫毛 颜色 1 黑色，2，棕色
//        @"lashStrength":@(1.0), //眼睫毛 取值范围为 [0.0, 1.0]
//
//        @"shadowStyle":@(0),//眼影 0 无, 1、2
//        @"shadowStrength":@(1.0),//取值范围为 [0.0, 1.0]
//
//        @"pupilStyle":@(0),//瞳孔类型 0 无, 1、2
//        @"pupilStrength":@(1.0),//取值范围为 [0.0, 1.0]。
//
//        @"blushStyle": @(0),  //腮红类型 0 无, 1、2
//        @"blushColor": @(0),  // 腮红颜色 0 无, 1、2、3、4、5
//        @"blushStrength":@(1.0),//取值范围为 [0.0, 1.0]
//
//        @"lipStyle":@(0),//唇彩  0 无, 1、2
//        @"lipColor":@(0),//颜色 0 无, 1、2、3、4、5
//        @"lipStrength":@(1.0),//取值范围为 [0.0, 1.0]
//        @"resPath":[Tool getMakeupResource],
//    }.mutableCopy;
//
//    
//    NSError *error = nil;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.makeupDict options:0 error:&error];
//    if (!jsonData || error) {
//        NSLog(@"JSON 转换失败: %@", error.localizedDescription);
//        return;
//    }
//    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    if (!jsonString) {
//        NSLog(@"JSON 字符串转换失败");
//        return;
//    }
//   
////    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
////    dispatch_async(queue, ^{
////        int retryCount = 0;
////        int sult = -1;
////
////        while (sult != 0) {  // 无限循环直到成功(sult == 0)
////            retryCount++;
////            NSLog(@"第 %d 次尝试 - 当前线程: %@", retryCount, [NSThread currentThread]);
////
//            int sult  = [self.agoraKit setExtensionPropertyWithVendor:@"agora_video_filters_clear_vision"
//                                                       extension:@"clear_vision"
//                                                             key:@"makeup_options"
//                                                           value:jsonString
//                                                      sourceType:AgoraMediaSourceTypePrimaryCamera];
//            NSLog(@"返回结果: %d", sult);
//            
////            if (sult == 0) {
////                NSLog(@"设置成功");
////                break;
////            }
////
////            // 添加延迟防止过于频繁调用
////            [NSThread sleepForTimeInterval:0.5];
////        }
////    });
////
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setBool:NO forKey:@"beautySwitchButton"];
//    [defaults setBool:NO forKey:@"makeUpBeautySwitchButton"];
//    [defaults synchronize];
//}


//#pragma mark - 美妆 设置 眉毛，眼睫毛，瞳孔，眼影
//- (void)makeUpButtonCurrentBigTitleIndex:(NSInteger)bigTitle withSubtitle:(NSInteger)subtitle
//{
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    if (bigTitle == 300) {
//        
//        NSInteger browStyle = 0;
//        if (subtitle == 400) {
//            
//            browStyle = 0;
//        }else if (subtitle == 401)
//        {
//            browStyle = 1;
//        }else{
//            browStyle = 2;
//        }
//    
//        self.makeupDict[@"browStyle"] = @(browStyle);
//        [defaults setInteger:browStyle forKey:@"browStyle"];
//        
//        
//    }else if (bigTitle == 301)
//    {
//        NSInteger lashStyle = 0;
//        if (subtitle == 401)
//        {
//            lashStyle = 3;
//        }else if(subtitle == 402){
//            lashStyle = 5;
//        }
//        self.makeupDict[@"lashStyle"] = @(lashStyle);
//        [defaults setInteger:lashStyle forKey:@"lashStyle"];
//
//        
//    }else if (bigTitle == 302)
//    {
//        NSInteger shadowStyle = 0;
//        if (subtitle == 401)
//        {
//            shadowStyle = 1;
//        }else if(subtitle == 402){
//            shadowStyle = 6;
//        }
//        self.makeupDict[@"shadowStyle"] = @(shadowStyle);
//        [defaults setInteger:shadowStyle forKey:@"shadowStyle"];
//        
//        
//    }
////    else if (bigTitle == 303)
////    {
////        NSInteger pupilStyle = 0;
////        if (subtitle == 400) {
////            pupilStyle = 1;
////        }else
////        {
////            pupilStyle = 2;
////        }
////
////
////        self.makeupDict[@"pupilStyle"] = @(pupilStyle);
////        [defaults setInteger:pupilStyle forKey:@"pupilStyle"];
////
////
////    }
//    self.makeupDict[@"resPath"] = [Tool getMakeupResource];
//    [self makeUPBaseJsonData:self.makeupDict];
//    [defaults synchronize];
//}
//#pragma mark - 美妆 设置 腮红，唇彩
//- (void)makeUpFourTitleIndex:(NSInteger)bigTitle withSubtitle:(NSInteger)subtitle
//{
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    if (bigTitle == 111) {
//
//        self.makeupDict[@"blushStyle"] = @(subtitle);
//        [defaults setInteger:subtitle forKey:@"blushStyle"];
//        
//    }else if (bigTitle == 222)
//    {
//        self.makeupDict[@"blushColor"] = @(subtitle);
//        [defaults setInteger:subtitle forKey:@"blushColor"];
//        
//    }else if (bigTitle == 333) {
//        self.makeupDict[@"lipStyle"] = @(subtitle);
//        [defaults setInteger:subtitle forKey:@"lipStyle"];
//    }else if (bigTitle == 444)
//    {
//        self.makeupDict[@"lipColor"] = @(subtitle);
//        [defaults setInteger:subtitle forKey:@"lipColor"];
//    }else if (bigTitle == 555)
//    {
//        self.makeupDict[@"browColor"] = @(subtitle);
//        [defaults setInteger:subtitle forKey:@"browColor"];
//    }else if (bigTitle == 666)
//    {
//        self.makeupDict[@"lashColor"] = @(subtitle);
//        [defaults setInteger:subtitle forKey:@"lashColor"];
//        
//    }
//    
//    self.makeupDict[@"resPath"] = [Tool getMakeupResource];
//    [self makeUPBaseJsonData:self.makeupDict];
//    
//    [defaults synchronize];
//}

- (void)makeUPBaseJsonData:(NSDictionary *)makeupParams
{
    // 将字典转换为 JSON 数据
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:makeupParams options:0 error:&error];
    if (!jsonData || error) {
        NSLog(@"JSON 转换失败: %@", error.localizedDescription);
        return;
    }

    // 将 JSON 数据转换为字符串
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (!jsonString) {
        NSLog(@"JSON 字符串转换失败");
        return;
    }

    // 调用 AgoraKit 的 setExtensionPropertyWithVendor 方法
 int result = [self.agoraKit setExtensionPropertyWithVendor:@"agora_video_filters_clear_vision"
                                       extension:@"clear_vision"
                                             key:@"makeup_options"
                                           value:jsonString sourceType:AgoraMediaSourceTypePrimaryCamera];
    
    NSLog(@"result %d",result);
}

//- (void)onEventWithContext:(AgoraExtensionContext * _Nonnull)context
//            key:(NSString * __nullable)key
//          value:(NSString * __nullable)value
//{
//    NSLog(@"1111");
//}


-(void)videoRationAction{
    
//    for(int i = 0;i<4;i++){
//        UIButton *button = [self.view viewWithTag:100+i+1];
//        if([self.buttonTitleArray[2] isEqualToString:self.buttonTitleArray[i+1]]){
//            [button setSelected:true];
//        }else{
//            [button setSelected:false];
//        }
//    }
//    
//    self.ratioView.hidden = false;
//    self.videoRatioButton.hidden = true;
//    self.ratioView.frame = CGRectMake(CGRectGetMinX(self.videoRatioButton.frame), CGRectGetMinY(self.videoRatioButton.frame), 40, 40);
//    __weak typeof(self) weakSelf = self;
//    [UIView animateWithDuration:0.3 animations:^{
//        weakSelf.ratioView.frame = CGRectMake(CGRectGetMinX(weakSelf.videoRatioButton.frame), CGRectGetMinY(weakSelf.videoRatioButton.frame), 40, 180);
//    } completion:^(BOOL finished) {
//        weakSelf.tapView.userInteractionEnabled = true;
//    }];
    ClarityBottomView *clarityAction = [[ClarityBottomView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 442)];
    clarityAction.delegate = self;
    [clarityAction showView];
    
}

#pragma mark - 清晰度
- (void)clarityButtonsAction:(NSInteger)index
{
    if(self.isLive&&!self.isAgoraRtc){
        [[ZXMessageCase shareInstace] showMessage:@"直播中不能切换清晰度"];
        return;
    }

    __weak typeof(self) weakSelf = self;
    if(self.isAgoraRtc){
        //码率 bitrate ，帧率 frameRate
        CGSize size = CGSizeZero;
        NSInteger bitrate = 0;
        NSInteger minBitrate = 0;
        NSString *buttonTitle = @"高清";
      
        switch (index) {
            case 0:
                {
                    size = CGSizeMake(360, 640);
                    bitrate = 800;
                    minBitrate = 600;
                    buttonTitle = @"流畅";
                }
                break;
            case 1:
                {
                    size = CGSizeMake(540, 960);
                    bitrate = 1200;
                    minBitrate = 800;
                    buttonTitle = @"标清";
                }
                break;
            case 2:
                {
                    ///高清
                    size = CGSizeMake(720, 1280);
                    bitrate = 2200;
                    minBitrate = 800;
                    buttonTitle = @"高清";
                }
                break;
            case 3:
                {
                    ///超清1080*1920，
                    size = CGSizeMake(1080, 1920);
                    bitrate = 3000;
                    minBitrate = 800;
                    buttonTitle = @"超清";
                }
                break;
            default:{
                ///高清
                size = CGSizeMake(720, 1280);
                bitrate = 2200;
                minBitrate = 800;
                buttonTitle = @"高清";
            }
                break;
        }
        
        self.videoBitrate = bitrate;
        self.agoraRtcSize = size;
        AgoraVideoEncoderConfiguration *encoderConfig = [[AgoraVideoEncoderConfiguration alloc] initWithSize:size frameRate:(AgoraVideoFrameRateFps24) bitrate:bitrate orientationMode:(AgoraVideoOutputOrientationModeFixedPortrait)mirrorMode:(AgoraVideoMirrorModeAuto)];
        encoderConfig.codecType = AgoraVideoCodecTypeH264;
        encoderConfig.minBitrate = minBitrate;//最小码率
        encoderConfig.degradationPreference = AgoraDegradationMaintainResolution;
        [self.agoraKit setVideoEncoderConfiguration:encoderConfig];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setInteger:self.videoBitrate forKey:@"videoBitrate"];
        [defaults setInteger:size.width forKey:@"agoraRtcSizeWith"];
        [defaults setInteger:size.height forKey:@"agoraRtcSizeHeight"];
        [defaults synchronize];
        
        [self.videoRatioButton setTitle:buttonTitle forState:0];
        
    }else{
        
        dispatch_async ( dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0 ), ^{
            //Fire api
            dispatch_async(dispatch_get_main_queue(), ^{
                //update interface
                [weakSelf.manager __init_qiniu_config:index+1 withView:weakSelf.view];
                if (weakSelf.isLive) {
                    [weakSelf.manager startPushStream];
                }
            });
        });
    }
}

- (void)sliderChangeValue:(NSInteger)value
{
    self.videoBitrate = value;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:self.videoBitrate forKey:@"videoBitrate"];
    [defaults synchronize];
    AgoraVideoEncoderConfiguration *encoderConfig = [[AgoraVideoEncoderConfiguration alloc] initWithSize:self.agoraRtcSize frameRate:(AgoraVideoFrameRateFps24) bitrate:self.videoBitrate orientationMode:(AgoraVideoOutputOrientationModeFixedPortrait)mirrorMode:(AgoraVideoMirrorModeAuto)];
    encoderConfig.codecType = AgoraVideoCodecTypeH264;
    encoderConfig.minBitrate = 800;//最小码率
    encoderConfig.degradationPreference = AgoraDegradationMaintainResolution;
    [self.agoraKit setVideoEncoderConfiguration:encoderConfig];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *value = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    CGRect keyboardRect = [value CGRectValue];
//    int height = keyboardRect.size.height;
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    //获取键盘的高度
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [value CGRectValue];
//    int height = keyboardRect.size.height;
    __weak typeof(self) weakSelf = self;
    [NSTimer scheduledTimerWithTimeInterval:0.25 repeats:NO block:^(NSTimer * _Nonnull timer) {
        weakSelf.chatInputView.hidden = true;
    }];
    
}

-(void)ratioTapAction{
    if(!self.ratioView.isHidden){
        self.ratioView.hidden = true;
        self.videoRatioButton.hidden = false;
        self.tapView.userInteractionEnabled = false;
    }
    
}

-(void)ticketAction{
    
}

-(void)loveAction{
    
}

-(void)linkAction{
    
}

-(void)messageAction{
    if (self.isMuteAll) {
        [[ZXMessageCase shareInstace] showMessage:@"管理员关闭了聊天功能"];
        return;
    }
    self.chatInputView.hidden = false;
    [self.chatTextView becomeFirstResponder];
}

-(void)tapAction{
    [self.chatInputView endEditing:YES];
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.chatInputView.frame = CGRectMake(0, 200, SCREEN_WIDTH, SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        weakSelf.chatInputView.hidden = true;
        weakSelf.chatInputView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

-(void)beginAction:(UIButton *)sender{
    
    if ([self afn] == 0) {
        [[ZXMessageCase shareInstace] showMessage:@"当前网络不可用，请检查网络!"];
        return;
    }
    
    
    if(self.isAgoraRtc){
        self.isAgoraRtcBegin = YES;
        //加入频道
        [self joinChannelByToken];
        
    }else{
        __weak typeof(self) weakSelf = self;
        sender.enabled = NO;
        [self.manager beginLiveSuccess:^(id  _Nonnull json) {
            sender.enabled = YES;
            if ([json[@"code"] intValue] == 200) {
                [weakSelf startLiveParams];
            }else{
                [[ZXMessageCase shareInstace] showMessage:json[@"msg"]];
            }
        } failure:^(id  _Nonnull error) {
            sender.enabled = YES;
            NSLog(@"error%@",error);
        }];
    }
}

-(NSInteger)afn
{
   __block NSInteger afnStatus = 1; // -1 或者0 是无网络可用

    // 创建一个 Reachability 对象
    Reachability *reachability = [Reachability reachabilityForInternetConnection];

    // 开始监控网络状态
    [reachability startNotifier];

    // 获取网络状态
    NetworkStatus status = [reachability currentReachabilityStatus];

    switch (status) {
        case NotReachable:
            NSLog(@"无网络可用");
            afnStatus = 0;
            break;
        case ReachableViaWiFi:
            NSLog(@"当前连接 WiFi");
            afnStatus = 2;
            break;
        case ReachableViaWWAN:
            NSLog(@"当前连接 4G");
            afnStatus = 1;
            break;
        default:
            break;
    }
    
    return afnStatus;
}
#pragma mark - 开始刷新在线人数

//- (void)startFreshOnline
//{
//    if (self.onlineTimer == nil)
//    {
//        self.onlineTimer = [NSTimer timerWithTimeInterval:1.0
//                                                      target:self
//                                                    selector:@selector(onlineRefresh)
//                                                    userInfo:nil
//                                                     repeats:YES];
//        [[NSRunLoop mainRunLoop] addTimer:self.onlineTimer forMode:NSRunLoopCommonModes];
//    }
//}

//- (void)onlineRefresh
//{
//    self.onLineSeconds--;
//    if (self.onLineSeconds == 0) {
//
////        [self dataRequest];
//        self.onLineSeconds = 30;
//    }
//}

//- (void)dataRequest
//{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer.timeoutInterval = 30.0f;
//   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
//    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/watch_user_list/%@/?page=1&size=100",HTTPSURL,self.roomID];
//
//    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
//    NSDictionary *dicheaders = @{@"authorization":[NSString stringWithFormat:@"JWT %@",dict[@"token"]]};
//    __weak typeof(self) weakSelf = self;
//    [manager GET:urlString parameters:nil headers:dicheaders progress:^(NSProgress * _Nonnull downloadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        NSArray<OnlineModel *>*array = [OnlineModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];
//
//        if (array.count!=0) {
//            weakSelf.peopleBtn.hidden = NO;
//            [weakSelf.peopleBtn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)array.count] forState:UIControlStateNormal];
//            weakSelf.peopleBtn.hidden = NO;
//            weakSelf.onlineLabel.hidden = YES;
//            weakSelf.headImgView.hidden = NO;
//            // 创建多个 UIImageView
//            NSArray *topThree = [NSArray new];
//            if(array.count>3){
//                topThree = [array subarrayWithRange:NSMakeRange(0, 3)];
//            }else{
//                topThree = array;
//            }
//
//            for(UIView *mylabelview in [weakSelf.headImgView subviews])
//            {
//                if ([mylabelview isKindOfClass:[UIImageView class]]) {
//                    [mylabelview removeFromSuperview];
//                }
//            }
//
//            for (int i = 0; i < topThree.count; i++) {
//                OnlineModel *model = topThree[i];
//                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(115-(i*35), 0, 30, 30)];
//                imageView.layer.cornerRadius = 15;
//                    imageView.clipsToBounds = YES;
//                [imageView sd_setImageWithURL:[NSURL URLWithString:model.headImageUrl]];
//                [weakSelf.headImgView addSubview:imageView];
//            }
//        }else{
//            weakSelf.onlineLabel.hidden = NO;
//            weakSelf.headImgView.hidden = YES;
//            weakSelf.peopleBtn.hidden = YES;
//        }
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//    }];
//}

-(void)closeAction{
    
    // 初始化对话框
    __weak typeof(self) weakSelf = self;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认关闭直播" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            
            if(weakSelf.isAgoraRtc){
                
                if (weakSelf.isAgoraRtcBegin) {//结束直播
                    [weakSelf endLiveAction];
                    
                }
                [weakSelf.manager leaveRoom];
                weakSelf.beginView.hidden = true;
                weakSelf.beginTimeLabel.hidden = true;
                weakSelf.beginButton.hidden = false;
                weakSelf.closeButton.hidden = true;
                [weakSelf.timer invalidate];
                weakSelf.timer = nil;
                weakSelf.isLive = false;
                if(weakSelf.onlineTimer!=nil){
                    [weakSelf.onlineTimer invalidate];
                    weakSelf.onlineTimer = nil;
                }
                
            }else{
                [weakSelf.manager stopLive:true suc:^(id  _Nonnull json) {
                                        
                    if ([json[@"code"] intValue] == 200) {
                        {
                            [weakSelf.manager leaveRoom];
                            weakSelf.beginView.hidden = true;
                            weakSelf.beginTimeLabel.hidden = true;
                            weakSelf.beginButton.hidden = false;
                            [weakSelf.manager.session stopStreaming];
                            weakSelf.closeButton.hidden = true;
                            [weakSelf.timer invalidate];
                            weakSelf.timer = nil;
                            weakSelf.isLive = false;
                            [weakSelf backAction];
                            if(weakSelf.onlineTimer!=nil){
                                [weakSelf.onlineTimer invalidate];
                                weakSelf.onlineTimer = nil;
                            }
                        }
                    }
                } failure:^(id  _Nonnull error) {
                    
                } ];
            }
        }];
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

        [alert addAction:okAction];
        [alert addAction:cancelAction];

        // 弹出对话框
        [self presentViewController:alert animated:true completion:nil];
    
    
}

-(void)bagAction{
    
    [self.liveGoodsVC show];
}

-(void)changeRatioAction:(UIButton *)button{
    
    if(self.isLive&&!self.isAgoraRtc){
        [[ZXMessageCase shareInstace] showMessage:@"直播中不能切换清晰度"];
        return;
    }
//    if(button.tag == 100){
//        return;
//    }
//    UIButton *first = [self.view viewWithTag:100];
//    
//    self.buttonTitleArray[0] = self.buttonTitleArray[button.tag-100];
//    [first setTitle:self.buttonTitleArray[0] forState:UIControlStateNormal];
//    [self.videoRatioButton setTitle:self.buttonTitleArray[0] forState:UIControlStateNormal];
//    [button setSelected:true];
    __weak typeof(self) weakSelf = self;
//    [UIView animateWithDuration:0.3 animations:^{
//        weakSelf.ratioView.frame = CGRectMake(CGRectGetMinX(weakSelf.videoRatioButton.frame), CGRectGetMinY(weakSelf.videoRatioButton.frame), 40, 40);
//    } completion:^(BOOL finished) {
//        weakSelf.ratioView.hidden = true;
//        weakSelf.videoRatioButton.hidden = false;
//        weakSelf.tapView.userInteractionEnabled = false;
//    }];
//    
    if(self.isAgoraRtc){
        //码率 bitrate ，帧率 frameRate
        CGSize size = CGSizeZero;
        NSInteger bitrate = 0;
        NSInteger minBitrate = 0;
        if(button.tag == 101){
            ///超清1080*1920，
            size = CGSizeMake(1080, 1920);
            bitrate = 3000;
            minBitrate = 800;
        }
        else if(button.tag == 102){
            ///高清
            size = CGSizeMake(720, 1280);
            bitrate = 2200;
            minBitrate = 800;
        }else if (button.tag == 103){
            
            size = CGSizeMake(540, 960);
            bitrate = 1200;
            minBitrate = 800;
            
        }else if (button.tag == 104)
        {
            size = CGSizeMake(360, 640);
            bitrate = 800;
            minBitrate = 600;
        }
        else{
            ///高清
            size = CGSizeMake(720, 1280);
            bitrate = 2200;
            minBitrate = 800;
        }
        self.videoBitrate = bitrate;
        AgoraVideoEncoderConfiguration *encoderConfig = [[AgoraVideoEncoderConfiguration alloc] initWithSize:size frameRate:(AgoraVideoFrameRateFps24) bitrate:bitrate orientationMode:(AgoraVideoOutputOrientationModeFixedPortrait)mirrorMode:(AgoraVideoMirrorModeAuto)];
        encoderConfig.codecType = AgoraVideoCodecTypeH264;
        encoderConfig.minBitrate = minBitrate;//最小码率
        encoderConfig.degradationPreference = AgoraDegradationMaintainResolution;
        [self.agoraKit setVideoEncoderConfiguration:encoderConfig];
        
    }else{
        if(button.tag == 101){
            
            dispatch_async ( dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0 ), ^{
                //Fire api
                dispatch_async(dispatch_get_main_queue(), ^{
                    //update interface
                    [weakSelf.manager __init_qiniu_config:WOOVideoQualityHigh withView:weakSelf.view];
                    if (weakSelf.isLive) {
                        [weakSelf.manager startPushStream];
                    }
                });
            });
            
        }else if(button.tag == 102){
            
            dispatch_async ( dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0 ), ^{
                //Fire api
                dispatch_async(dispatch_get_main_queue(), ^{
                    //update interface
                    [weakSelf.manager __init_qiniu_config:WOOVideoQualityMedium withView:weakSelf.view];
                    if (weakSelf.isLive) {
                        [weakSelf.manager startPushStream];
                    }
                });
            });
        }else{
            
            dispatch_async ( dispatch_get_global_queue ( DISPATCH_QUEUE_PRIORITY_DEFAULT , 0 ), ^{
                //Fire api
                dispatch_async(dispatch_get_main_queue(), ^{
                    //update interface
                    [weakSelf.manager __init_qiniu_config:WOOVideoQualityLow withView:weakSelf.view];
                    if (weakSelf.isLive) {
                        [weakSelf.manager startPushStream];
                    }
                });
            });
        }
    }
}
#pragma mark - 初始化SDK
-(void)initEngine{
    
    // 这里是摄像头可以使用的处理逻辑
    self.manager = [YouinRTCManager shardManager];
    
    // 遵循代理YouinRTCDelegate
    self.manager.delegate = self;
    self.manager.chatDelegate = self;
    //声网
#warning 声网
    if(self.isAgoraRtc){
                
        if (self.isAgoraRtcBeauty) {
            self.faceBeautyView = [[FaceBeautyBottomView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 280)];
            [self.faceBeautyView hideView];
            // FaceUnity
            [FUDemoManager setupFUSDK];
            [[FUDemoManager shared] addDemoViewToView:self.faceBeautyView originY:280-FUBottomBarHeight];
        }
       
        
        // 调用初始化视频窗口函数
            [self initViews];
            // 后续步骤调用声网 API 使用的函数
            [self initializeAgoraEngine];
            [self setupLocalVideo];
        
        // 注册解锁通知
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(screenDidUnlock)
                                                     name:UIApplicationDidBecomeActiveNotification
                                                   object:nil];
        
        bool isCamare = [Tool safeIntForKey:@"camera-direction" defaultValue:1];
        _isFrontCamera = isCamare;
        if (self.isAgoraRtcBeauty)
        {
            [[FUDemoManager shared] setCurrentBeauty];
        }
      
    }else{
        // 主播端
        self.manager.modouleFunc = YouinModuleFuncLive;
        // 将预览界面放在View上
        [self.manager __init_qiniu_config:WOOVideoQualityHigh withView:self.view];
        
        // 使用前置摄像头采集
        self.manager.captureDevicePosition = AVCaptureDevicePositionFront;
        // 开启美颜
        [self.manager setBeautifyModeOn:YES];
    }
    // 加入指定房间
    [[YouinRTCManager shardManager] joinRoom:self.roomID callback:^(BOOL success, NSError * _Nullable error) {
        if(success){
            [[ZXMessageCase shareInstace] showMessage:@"进入房间..."];
        }
    }];
    [self.manager.session startCaptureSession];
}

#pragma mark 代理
- (void)YouinMediaStreamingSession:(PLMediaStreamingSession *)session streamStateDidChange:(PLStreamState)state
{
    switch (state) {
        case PLStreamStateConnected:
        {
            NSLog(@"连接成功");
            [[ZXMessageCase shareInstace] showMessage:@"房间已连接"];
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //快速重连
//                [self.manager.session restartStreamingWithFeedback:^(PLStreamStartStateFeedback feedback) {
//                    NSLog(@"PLStreamStartStateSuccess--");
//                }];
//            });
            
            break;
        }
        case PLStreamStateAutoReconnecting:{
            [[ZXMessageCase shareInstace] showMessage:@"重新连接中"];
//            [self startTimer];
            break;
        }
        case PLStreamStateDisconnected:{
            
            [[ZXMessageCase shareInstace] showMessage:@"断开连接"];
            break;
        }

        default:
            break;
    }
}

//    重连后失败
- (void)YouinMediaStreamingSession:(PLMediaStreamingSession *)session didDisconnectWithError:(NSError *)error
{
    
    __weak typeof(self) weakSelf = self;
    self.heatBeat =  [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        weakSelf.reConnectTime++;
        
        if (weakSelf.reConnectTime >= 4) {
            if (weakSelf.heatBeat) {
                [weakSelf.heatBeat invalidate];
                weakSelf.heatBeat = nil;
            }
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前网络不佳被迫退出直播间" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //确定退出
                [weakSelf quitRoom:YES];
            }];
            [alert addAction:actionConfirm];
            [weakSelf presentViewController:alert animated:YES completion:nil];
            return;
        }
        //用重连间隔加倍的方式
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(weakSelf.reConnectTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //重启两次
//            NSLog(@"_retryCount22==%d",weakSelf._retryCount);
//            NSLog(@"_reConnectTime22==%d",self->_reConnectTime);

         });
         
         
    }];
    [[NSRunLoop currentRunLoop] addTimer:_heatBeat forMode:NSRunLoopCommonModes];
}


- (void)isEndLive
{
    [PrivateChatView clearSharedView];
    self.beginView.hidden = true;
    self.beginTimeLabel.hidden = true;
    self.beginButton.hidden = false;
    self.closeButton.hidden = true;
    self.isLive = false;
    //声网
    [self leaveChannel];
    [self startLiveAndStopWithAction:@"publish_done"];
   
    [self.timer invalidate];
    self.timer = nil;
    [self.chatTable.view setHidden:true];
    if(self.onlineTimer!=nil){
        [self.onlineTimer invalidate];
        self.onlineTimer = nil;
    }
    if(self.enterTimer!=nil){
        [self.enterTimer invalidate];
        self.enterTimer = nil;
    }
    
    if (self.heatBeat!=nil) {
        [self.heatBeat invalidate];
        self.heatBeat = nil;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    [self dataToShow];
//    LiveStreamDataViewController *liveVC = [[LiveStreamDataViewController alloc] init];
//    liveVC.liveid = self.roomID;
//    [self.navigationController pushViewController:liveVC animated:YES];
    
}

- (void)quitRoom:(BOOL)isForceQuit
{
    [PrivateChatView clearSharedView];
    self.beginView.hidden = true;
    self.beginTimeLabel.hidden = true;
    self.beginButton.hidden = false;
    self.closeButton.hidden = true;
    self.isLive = false;
    //声网
    if(self.isAgoraRtc){
        [self leaveChannel];
        if (!isForceQuit) {//是否网络问题被迫退出
            [self startLiveAndStopWithAction:@"publish_done"];
        }
        
    }else{
        [self.manager.session stopStreaming];
        [self.manager stopLive:false suc:^(id  _Nonnull json) {
            
        } failure:^(id  _Nonnull error) {
            
        }];
        [self.manager leaveRoom];
    }
   
    [self.timer invalidate];
    self.timer = nil;
    [self.chatTable.view setHidden:true];
    if(self.onlineTimer!=nil){
        [self.onlineTimer invalidate];
        self.onlineTimer = nil;
    }
    if(self.enterTimer!=nil){
        [self.enterTimer invalidate];
        self.enterTimer = nil;
    }
    
    if (self.heatBeat!=nil) {
        [self.heatBeat invalidate];
        self.heatBeat = nil;
    }

    [self.navigationController popViewControllerAnimated:YES];

}
// 合流
-(void)mergeTrack{
    [[ZXMessageCase shareInstace] showMessage:@"直播已开始"];
}

-(void)courseInfo:(CourseModel *)courseInfoModel error:(NSError *)error{
    if(courseInfoModel){
        self.corseInfoModel = courseInfoModel;
        [self getTimeCount:courseInfoModel];
        // 预加载商品页
        // 商品
        self.liveGoodsVC = [LiveGoodsViewController new];
        self.liveGoodsVC.liveId = self.roomID;
        self.liveGoodsVC.enterpriseId = self.corseInfoModel.enterprise_id;
        self.liveGoodsVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        [self addChildViewController:self.liveGoodsVC];
        [self.view addSubview:self.liveGoodsVC.view];
        [self.liveGoodsVC didMoveToParentViewController:self];
        self.liveGoodsVC.view.hidden = true;
        
        
        // 获取历史消息
        __weak typeof(self) weakSelf = self;
        [[YouinRTCManager shardManager] getHistoryMessage:100 callback:^(NSArray<BaseMessageModel *> * _Nonnull message, NSError * _Nullable error) {
            // messageType -1  文字信息  -2 图片信息
            for(BaseMessageModel *i in message){
                i.color = rgba(arc4random() % 256, arc4random() % 256, arc4random() % 256, 1);
            }
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [weakSelf.chatTable.messageArray addObjectsFromArray:message];
            weakSelf.chatTable.messageArray = [NSMutableArray arrayWithArray:[[weakSelf.chatTable.messageArray reverseObjectEnumerator] allObjects]];
            [weakSelf.chatTable.tableView reloadData];
            [weakSelf.chatTable.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
        }];
    }
}

-(void)enterpriseInfo:(EnterpriseModel *)enterpriseModel error:(NSError *)error{
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:enterpriseModel.frontend_logo]];
    self.titleLabel.text = enterpriseModel.short_name;
    //获取在线列表权限
    [self getPermissionListRequest:enterpriseModel.enterprise_id];
}

-(void)statusInfo:(StatusModel *)statusModel error:(NSError *)error{
    self.dataModel = statusModel;
    self.watchLabel.text = [NSString stringWithFormat:@"%d次访问 %d赞",statusModel.pv_count,statusModel.like_count];
    self.loveLabel.text = [NSString stringWithFormat:@"%d",statusModel.like_count];
    
    [self.onlinePeopleView updateCount:statusModel.current_watch_count totalCount:statusModel.max_watch_count];
}


- (void)enterpriseJson:(NSDictionary *)enterpriseDict error:(NSError *)error
{
    
    if (enterpriseDict != nil && enterpriseDict.count != 0) {
        self.isAgoraRtcBeauty = [enterpriseDict[@"beauty_filter"] intValue];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // 创建定时器，并每秒钟检查一次进入时间数组
    self.enterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkEnterTime) userInfo:nil repeats:YES];
}

// 定时器回调函数
- (void)checkEnterTime {
    // 获取当前时间戳
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];

    // 遍历进入时间数组，查找已经超过一定时间的时间戳，并将其从数组中删除
    for (NSInteger i = self.enterTimeArray.count - 1; i >= 0; i--) {
        NSTimeInterval enterTime = [self.enterTimeArray[i] doubleValue];
        if (currentTime - enterTime > 3.0) {
            [self.enterTimeArray removeObjectAtIndex:i];
        
            // 从父视图中移除对应的进入提示视图
            UIView *tipView = [self.view viewWithTag:1000 + i];
            [tipView removeFromSuperview];
        }
    }
}
#pragma mark - 收到IM消息
-(void)onNewMessageRecive:(BaseMessageModel *)messageModel{
    
    if ([messageModel.ws_type isEqualToString:@"private_chat_add"]) {
        //主播自己不用提示消息
        if(self.corseInfoModel.user_id != messageModel.send){
            //保存私聊列表的用户id
            [self.privateModel.userIdArr addObject:messageModel.send];
            //私聊信息
            [self.player play];
            self.redPoint.hidden = NO;
            
            PrivateChatView *chatView = [PrivateChatView sharedView];
            PrivateModel *priModel = [PrivateModel new];
            priModel.liveId = self.roomID;
            priModel.token = self.token;
            priModel.userName = messageModel.send_nickname;
            priModel.userId = messageModel.send;
            priModel.userIdArr = self.privateModel.userIdArr;
            chatView.model = priModel;
            
    //        [chatView show];
        }
        
                
    }else if([messageModel.ws_type isEqualToString:@"newUserJoinRoom"]){

        // 记录进入时间
        NSTimeInterval enterTime = [[NSDate date] timeIntervalSince1970];
        [self.enterTimeArray addObject:@(enterTime)];
        [self.enterNameArray addObject:messageModel.nickName];

        
        // 创建进入提示视图
        EnterTipView *tipView = [[EnterTipView alloc] initWithFrame:CGRectMake(0,SCREEN_HEIGHT, SCREEN_WIDTH-30, 40)];
        [tipView.btnTitle setTitle:[NSString stringWithFormat:@"%@ 进入了直播间",messageModel.nickName] forState:0];
        CGSize size = [tipView.btnTitle.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: tipView.btnTitle.titleLabel.font}];
        CGFloat width = size.width;
        // 设置进入提示视图的宽度
        CGRect frame = tipView.frame;
        frame.size.width = width + 40.0; // 加上左右边距
        tipView.frame = frame;
        
        // 将进入提示视图添加到父视图中
        [self.view addSubview:tipView];
        // 将进入提示视图保存到数组中，以便后续排序
        [self.enterTipViews addObject:tipView];
        __weak typeof(self) weakSelf = self;
        // 动画显示进入提示视图
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = tipView.frame;
            frame.origin.y = weakSelf.chatTable.view.frame.origin.y+weakSelf.enterTipViews.count * 30;
            tipView.frame = frame;
        } completion:^(BOOL finished) {
            // 动画完成后，延迟一定时间后隐藏进入提示视图
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.3 animations:^{
                    CGRect frame = tipView.frame;
                    frame.origin.x = -SCREEN_WIDTH;
                    tipView.frame = frame;
                } completion:^(BOOL finished) {
                    // 动画完成后，从父视图中移除进入提示视图
                    [tipView removeFromSuperview];
                    [weakSelf.enterTipViews removeObject:tipView];
                }];
            });
        }];
        
        
        [self sortEnterTipsByTime];
    }
    else{
        // messageType -1  文字信息  -2 图片信息
        messageModel.color = rgba(arc4random() % 256, arc4random() % 256, arc4random() % 256, 1);
        [self.chatTable.messageArray insertObject:messageModel atIndex:0];
//        [self.chatTable refreshGift];
        [self.chatTable.tableView reloadData];
        [self.chatTable.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

        if(messageModel.isGift){
            // 礼物消息

        }
    }

}

- (void)sortEnterTipsByTime {
    // 先移除超过5个的进入提示视图
    if (self.enterTipViews.count > 5) {
        NSInteger removeCount = self.enterTipViews.count - 5;
        for (NSInteger i = 0; i < removeCount; i++) {
            EnterTipView *tipView = self.enterTipViews[i];
            [tipView removeFromSuperview];
        }
        [self.enterTipViews removeObjectsInRange:NSMakeRange(0, removeCount)];
    }

    // 根据进入时间戳排序
    NSArray *sortedArray = [self.enterTimeArray sortedArrayUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
        NSTimeInterval time1 = [obj1 doubleValue];
        NSTimeInterval time2 = [obj2 doubleValue];
        return time1 - time2;
    }];

    // 重新排列进入提示视图的位置
    for (NSInteger i = 0; i < sortedArray.count; i++) {
        NSTimeInterval enterTime = [sortedArray[i] doubleValue];
        NSInteger index = [self.enterTimeArray indexOfObject:@(enterTime)];
        if (index != NSNotFound && index < self.enterTipViews.count) {
            EnterTipView *tipView = self.enterTipViews[index];
            CGRect frame = tipView.frame;
            frame.origin.y = self.chatTable.view.frame.origin.y + i * 30;
            tipView.frame = frame;
        }
    }
    __weak typeof(self) weakSelf = self;
    // 如果当前屏幕上显示的进入提示视图数量超过了5个，则移除多余的进入提示视图
    if (self.enterTipViews.count > 5) {
        for (NSInteger i = self.enterTipViews.count - 1; i >= 5; i--) {
            EnterTipView *tipView = self.enterTipViews[i];
            [UIView animateWithDuration:0.3 animations:^{
                CGRect frame = tipView.frame;
                frame.origin.x = -SCREEN_WIDTH;
                tipView.frame = frame;
            } completion:^(BOOL finished) {
                [tipView removeFromSuperview];
                [weakSelf.enterTipViews removeObjectAtIndex:i];
            }];
        }
    }
}
-(void)getTimeCount:(CourseModel*)model{
    long currentTime =  [[NSDate date] timeIntervalSince1970];
    long beginTime = [self cTimestampFromString:model.start_time];
    if(currentTime >= beginTime){
        self.timeLabel.hidden = true;
        self.timeCountLabel.hidden = true;
    }else{
        self.timeLabel.hidden = false;
        self.timeCountLabel.hidden = false;
        self.timeCount = beginTime-currentTime;
        __weak typeof(self) weakSelf = self;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            weakSelf.timeCount -= 1;
            int hour = weakSelf.timeCount/3600;
            int minutes = weakSelf.timeCount%3600/60;
            int seconds = weakSelf.timeCount%60;
            weakSelf.timeCountLabel.text = [NSString stringWithFormat:@"%02d小时%02d分钟%02d秒",hour,minutes,seconds];
        }];
    }
}

-(long )cTimestampFromString:(NSString *)theTime {
    // 转换为时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate* dateTodo = [formatter dateFromString:theTime];
    return  (long)[dateTodo timeIntervalSince1970];
   
}

#pragma mark - 在线人数
- (void)onlineBtnAction
{
    OnlinePeopleView *view = [[OnlinePeopleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8)];
    view.delegate = self;
    self.privateModel.liveId = self.roomID;
    self.privateModel.token = self.token;
    view.model = self.privateModel;
    [view show];
}
#pragma mark - 判断红点是否消失
- (void)ClearRedPoint:(NSInteger)count
{
    if(count == 0){
        self.redPoint.hidden = YES;
    }else{
        self.redPoint.hidden = NO;
    }
}
#pragma mark - 获取是否支持在线列表的权限
- (void)getPermissionListRequest:(NSString *)enterprise_id
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/enterprise/system/get_permission_list/%@/",HTTPSURL,enterprise_id];
    NSDictionary *auth = @{@"authorization":[NSString stringWithFormat:@"jwt %@",self.token]};
    __weak typeof(self) weakSelf = self;
    [manager GET:urlString parameters:nil headers:auth progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        "watch_user':# true 开启在线观众列表显示;false 不显示在线观众列表
//        "private_chat":false,# treu 允许私聊，false 不允许私聊，不显示私聊按钮
//        一个权限是私聊，有私聊就有在线列表；"
//        一个权限是在线列表，有在线列表时，仅有在线列表功能，不能私聊。
        if([responseObject[@"code"] intValue] == 200){
            weakSelf.privateModel.private_chat = [responseObject[@"result"][@"private_chat"] intValue];
            weakSelf.privateModel.watch_user = [responseObject[@"result"][@"watch_user"] intValue];
            if([responseObject[@"result"][@"private_chat"] intValue]==1||[responseObject[@"result"][@"watch_user"] intValue]==1){
                weakSelf.onlineBtn.hidden = NO;
            }else{
                //无权限显示在线列表
                weakSelf.onlineBtn.hidden = YES;
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - 主播 禁言 && 拉黑 ， 取消全部禁言(需要找到后台的字段)，问下直播的身份type
- (void)rtcChatForbiddenWithPerson:(BaseMessageModel *)msdModel
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"主播权限提示" preferredStyle:UIAlertControllerStyleActionSheet];

     UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
         
     }];
   
     UIAlertAction *jinyan = [UIAlertAction actionWithTitle:@"禁言此人" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
         
         [RYAlertController showAlertWithTitle:@"禁言此人" message:@"确定禁言此人吗？" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
             alertMaker.addActionDefaultTitle(@"取消").addActionDestructiveTitle(@"确定");
         } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
             if (buttonIndex == 1) {
                 
                 NSDictionary *dict = @{@"image":msdModel.avatar,@"nickname":msdModel.nickName,@"user_id":msdModel.userId,@"liveId":weakSelf.roomID};

                 [[YouinRTCManager shardManager] getAddForbidden:dict successBloc:^(id  _Nonnull json) {
                     
                     [[ZXMessageCase shareInstace] showMessage:@"禁言成功"];
                 } failure:^(NSError * _Nonnull error) {

                 }];
             }
         }];
         
     }];
    NSString *title = @"";
    if (self.isMuteAll) {
        title = @"取消全员禁言";
    }else
    {
        title = @"全员禁言";
    }
    UIAlertAction *jinyanAll = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [RYAlertController showAlertWithTitle:title message:[NSString stringWithFormat:@"确定要%@吗?",title] appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
            alertMaker.addActionDefaultTitle(@"取消").addActionDestructiveTitle(@"确定");
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                
                weakSelf.isMuteAll = !weakSelf.isMuteAll;
                NSString *str = @"";
                if (weakSelf.isMuteAll) {
                    str = @"全员禁言成功";
                }else
                {
                    
                    str = @"取消全员禁言成功";
                }
               
                [[YouinRTCManager shardManager] forbiddenAll:weakSelf.isMuteAll successBloc:^(id  _Nonnull json) {
                } failure:^(NSError * _Nonnull error) {
                    
                }];
            }
        }];
        
    }];
         

     UIAlertAction *kikout = [UIAlertAction actionWithTitle:@"踢出直播间" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
                  
         [RYAlertController showAlertWithTitle:@"踢出直播间" message:@"确定踢出直播间吗？" appearanceProcess:^(RYAlertController * _Nonnull alertMaker) {
             alertMaker.addActionDefaultTitle(@"取消").addActionDestructiveTitle(@"确定");
         } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, RYAlertController * _Nonnull alertSelf) {
             if (buttonIndex == 1) {
                 NSDictionary *dict = @{@"image":msdModel.avatar,@"nickname":msdModel.nickName,@"user_id":msdModel.userId,@"course_id":weakSelf.roomID};

                 [[YouinRTCManager shardManager] getAddKickOut:dict successBloc:^(id  _Nonnull json) {
                     
                     [[ZXMessageCase shareInstace] showMessage:@"踢出成功"];
                 } failure:^(NSError * _Nonnull error) {

                 }];
             }
         }];
     }];
     
    [alertController addAction:cancle];
    [alertController addAction:jinyan];
    [alertController addAction:jinyanAll];
     [alertController addAction:kikout];
     [self presentViewController:alertController animated:true completion:nil];
}

- (void)forbiddenBtnAction
{
    
    BottomAlertActionView *alertAction = [[BottomAlertActionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 236)];
    alertAction.deledate = self;
    [alertAction showView];
//    __weak typeof(self) weakSelf = self;
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    
//    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//        
//    }];
//        
//    UIAlertAction *jinyan = [UIAlertAction actionWithTitle:@"禁言列表" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//        
        
//
//    }];
//    
//    UIAlertAction *tongji = [UIAlertAction actionWithTitle:@"直播数据" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//           
//       // do something
//        [weakSelf dataToShow];
//       
//    }];
//
//    UIAlertAction *kikout = [UIAlertAction actionWithTitle:@"黑名单" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//           
//        [[YouinRTCManager shardManager] getListKickOut:weakSelf.roomID successBloc:^(id  _Nonnull json) {
//            
//            ForbiddenView *view = [[ForbiddenView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8)];
//            view.arrayModel = json;
//            view.isForbidden_words = NO;
//            view.isBlock = YES;
//            [view show];
//            
//        } failure:^(NSError * _Nonnull error) {
//            
//        }];
//       
//    }];
//    
//    [alertController addAction:cancle];
//    [alertController addAction:jinyan];
//    [alertController addAction:tongji];
//    [alertController addAction:kikout];
//    [self presentViewController:alertController animated:true completion:nil];
}

- (void)bottomActions:(UIButton *)sender
{
        __weak typeof(self) weakSelf = self;
    switch (sender.tag) {
        case 100:
        {
            [[YouinRTCManager shardManager] getListForbiddenWords:weakSelf.roomID successBloc:^(id  _Nonnull json) {
                
                ForbiddenView *view = [[ForbiddenView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8)];
                view.arrayModel = json;
                view.isForbidden_words = YES;
                view.isBlock = NO;
                [view show];
                
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }
            break;
        case 101:
        {
            [weakSelf dataToShow];
        }
            break;
        case 102:
        {
            [[YouinRTCManager shardManager] getListKickOut:weakSelf.roomID successBloc:^(id  _Nonnull json) {
                
                ForbiddenView *view = [[ForbiddenView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT/3.0*1.8)];
                view.arrayModel = json;
                view.isForbidden_words = NO;
                view.isBlock = YES;
                [view show];
                
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }
            break;
            
        default:
            break;
    }
}


#pragma mark - 数据统计
- (void)dataToShow{
    
    LiveStreamingData *liveData = [[LiveStreamingData alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-180)];
    [liveData showView];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    NSString *urlString = [NSString stringWithFormat:@"%@v1/statistics/system/analysis/%@/?&new_shop=1",HTTPSURL,self.roomID];
//    __weak typeof(self) weakSelf = self;
    
    NSString *token = [NSString stringWithFormat:@"JWT %@",self.token];
    [manager GET:urlString parameters:nil headers:@{@"authorization":token} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            [liveData liveData:responseObject[@"result"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
//
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(50, 0, SCREEN_WIDTH-100, SCREEN_HEIGHT/2-50)];
//    view.backgroundColor = [UIColor whiteColor];
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, view.frame.size.width-30, 30)];
//    label.text = @"直播数据";
//    label.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
//    label.textColor = [UIColor blackColor];
//    label.textAlignment = NSTextAlignmentCenter;
//    [view addSubview:label];
//    
//    //当前在线和最高在线
//    
//    UILabel *peopleCount = [[UILabel alloc] initWithFrame:CGRectMake(15, 15+label.frame.size.height+label.frame.origin.y, view.frame.size.width-30, 30)];
//    peopleCount.text = @"当前在线/最高在线";
//    peopleCount.font = [UIFont systemFontOfSize:14];
//    peopleCount.textColor = [UIColor darkGrayColor];
//    peopleCount.textAlignment = NSTextAlignmentCenter;
//    [view addSubview:peopleCount];
//    
//    
//    UILabel *peopleValue = [[UILabel alloc] initWithFrame:CGRectMake(15, peopleCount.frame.size.height+peopleCount.frame.origin.y+5, view.frame.size.width-30, 20)];
//    peopleValue.text = [NSString stringWithFormat:@"%d/%d",self.dataModel.current_watch_count,self.dataModel.max_watch_count];
//    peopleValue.font = [UIFont systemFontOfSize:16];
//    peopleValue.textColor = [UIColor systemGreenColor];
//    peopleValue.textAlignment = NSTextAlignmentCenter;
//    [view addSubview:peopleValue];
//    
//    float width1 = (view.frame.size.width)/2;
//    NSArray *arr1 = @[@"总访问人次",@"点赞数",@"总访问人数",@"转发数"];
//    NSArray *dataArr = @[@(self.dataModel.pv_count),@(self.dataModel.like_count),@(self.dataModel.uv_count),@(self.dataModel.share_count)];
//    for (int i =0; i < arr1.count; i ++) {
//        //行号
//        int row = i / 2;
//        //列号
//        int col = i % 2;
//        
//        CGFloat xibViewX = col * width1;
//        
//        CGFloat xibViewY = 30+ row * 70;
//
//        
//        UILabel *peopleTimes = [[UILabel alloc] initWithFrame:CGRectMake(xibViewX, (peopleValue.frame.size.height+peopleValue.frame.origin.y)+xibViewY, width1, 70)];
//        peopleTimes.text = arr1[i];
//        peopleTimes.font = [UIFont systemFontOfSize:14];
//        peopleTimes.textColor = [UIColor darkGrayColor];
//        peopleTimes.textAlignment = NSTextAlignmentCenter;
//        [view addSubview:peopleTimes];
//        
//        
//        UILabel *value = [[UILabel alloc] initWithFrame:CGRectMake(xibViewX, peopleTimes.frame.size.height+peopleTimes.frame.origin.y-15, width1, 20)];
//        value.text = [NSString stringWithFormat:@"%@",dataArr[i]];
//        value.font = [UIFont systemFontOfSize:16];
//        value.textColor = [UIColor systemGreenColor];
//        value.textAlignment = NSTextAlignmentCenter;
//        [view addSubview:value];
//    }
//    
//    
//    view.layer.cornerRadius = 10;
//    view.clipsToBounds = YES;
//    LSTPopView *popView = [LSTPopView initWithCustomView:view
//                                                popStyle:LSTPopStyleFade
//                                            dismissStyle:LSTDismissStyleFade];
//    popView.hemStyle = LSTHemStyleCenter;
//    LSTPopViewWK(popView);
//    popView.popDuration = 0.5;
//    popView.dismissDuration = 0.5;
//    popView.isClickFeedback = YES;
//    popView.bgClickBlock = ^{
//        NSLog(@"点击了背景");
//        [wk_popView dismiss];
//    };
//    [popView pop];
}

- (PrivateModel *)privateModel
{
    if(!_privateModel){
        _privateModel = [[PrivateModel alloc] init];
    }
    return  _privateModel;
}


#pragma mark - 声网
- (void)initViews {

    //强制不息屏
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    self.localView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:self.localView];
}

// ViewController.m
- (void)initializeAgoraEngine {
    
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject
                         stringByAppendingPathComponent:@"agora_logs"];
    
    
    // 打印路径（调试时查看）
    NSLog(@"Agora 日志路径：%@", cachePath);

    // 配置日志
    AgoraLogConfig *logConfig = [[AgoraLogConfig alloc] init];
    logConfig.filePath = cachePath;
    logConfig.level = AgoraLogLevelInfo;
    logConfig.fileSizeInKB = 2048;
    
    
    
    // set up agora instance when view loaded
    AgoraRtcEngineConfig *config = [[AgoraRtcEngineConfig alloc] init];
    config.appId = self.channelAppId;
    config.channelProfile = AgoraChannelProfileLiveBroadcasting;
    config.logConfig = logConfig;
    self.agoraKit = [AgoraRtcEngineKit sharedEngineWithConfig:config delegate:self];
    if (self.isAgoraRtcBeauty) {
        [self.agoraKit setVideoFrameDelegate:self];
    }
    
    // make myself a broadcaster
    [self.agoraKit setClientRole:(AgoraClientRoleBroadcaster)];
    // enable video module and set up video encoding configs
    [self.agoraKit enableAudio];
    [self.agoraKit enableVideo];
    
    // 读取
    self.baseBeautifyOption = [[AgoraBeautyOptions alloc] init];
    self.baseBeautifyOption.lighteningLevel = [Tool safeFloatForKey:@"BeautifyLighteningLevel" defaultValue:0.5];//亮度
    self.baseBeautifyOption.rednessLevel = [Tool safeFloatForKey:@"BeautifyRednessLevel" defaultValue:0.5];//红润
    self.baseBeautifyOption.sharpnessLevel = [Tool safeFloatForKey:@"BeautifySharpnessLevel" defaultValue:0.5];//锐度
    self.baseBeautifyOption.smoothnessLevel = [Tool safeFloatForKey:@"BeautifySmoothnessLevel" defaultValue:0.5];//平滑
    
    BOOL isBeautyOpen = [Tool safeIntForKey:@"beautySwitchButton" defaultValue:1];
    self.isOpenBeauty = isBeautyOpen;
    //默认打开基础美颜
    [self.agoraKit setBeautyEffectOptions:YES options:self.baseBeautifyOption];
    
//    //进阶美颜
//    self.beautyOptions = [[AgoraFaceShapeBeautyOptions alloc] init];
//    // 设置美型风格类型女性
//    self.beautyOptions.shapeStyle = AgoraFaceShapeStyleFemale;
//    // 设置风格强度
//    self.beautyOptions.styleIntensity = 50;
//    [self.agoraKit setFaceShapeBeautyOptions:isBeautyOpen options:self.beautyOptions];
    
  
////    // 创建 AgoraFaceShapeAreaOptions 对象 --- 美型
//    AgoraFaceShapeAreaOptions *areaOptions = [[AgoraFaceShapeAreaOptions alloc] init];
//    // 指定一个微调的部位，比如：头部尺寸
//    areaOptions.shapeArea = AgoraFaceShapeAreaHeadScale;
//    // 该部位调整的强度
//    areaOptions.shapeIntensity = 100;
//    // 调用 AgoraKit 的方法设置面部微调选项
//    [self.agoraKit setFaceShapeAreaOptions:areaOptions];
    //关闭美型
//    [self.agoraKit setFaceShapeBeautyOptions:false options:nil];
}

// ViewController.m
- (void)setupLocalVideo {
    
    
    NSInteger segmentIndex = [Tool safeIntForKey:@"agoraRtcSizeWith" defaultValue:self.version_id == 18?720:540];
    NSInteger videoBitrateValue = [Tool safeIntForKey:@"videoBitrate" defaultValue:self.version_id == 18?2200:1200];
    self.videoBitrate = videoBitrateValue;
    CGSize size = CGSizeMake(720, 1280);
    if (segmentIndex == 1080) {
        
        size = CGSizeMake(1080, 1920);
    }else if(segmentIndex == 720)
    {
        size = CGSizeMake(720, 1280);
    }else if(segmentIndex == 540)
    {
        size = CGSizeMake(540, 960);
        
    }else if(segmentIndex == 360){
        size = CGSizeMake(360, 640);
    }
    NSInteger mirrorIndex = [Tool safeIntForKey:@"Mirror-direction" defaultValue:1];
//    sender.selected?AgoraVideoMirrorModeDisabled:AgoraVideoMirrorModeEnabled
    AgoraVideoEncoderConfiguration *encoderConfig = [[AgoraVideoEncoderConfiguration alloc] initWithSize:size frameRate:(AgoraVideoFrameRateFps24) bitrate:self.videoBitrate orientationMode:(AgoraVideoOutputOrientationModeFixedPortrait)mirrorMode:(  mirrorIndex==2?AgoraVideoMirrorModeDisabled:AgoraVideoMirrorModeEnabled)];
    encoderConfig.codecType = AgoraVideoCodecTypeH264;
    encoderConfig.minBitrate = 800;//最小码率
    encoderConfig.degradationPreference = AgoraDegradationMaintainResolution;
    
    [self.agoraKit setVideoEncoderConfiguration:encoderConfig];
    
    // set up local video to render your local camera preview
    AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
    videoCanvas.uid = [self.roomID intValue];
    // the view to be binded
    videoCanvas.view = self.localView;
    videoCanvas.renderMode = AgoraVideoRenderModeHidden;
    [self.agoraKit setupLocalVideo:videoCanvas];
    // you have to call startPreview to see local video
    [self.agoraKit startPreview];
    //设置前置和后置摄像头
    AgoraCameraCapturerConfiguration *config = [[AgoraCameraCapturerConfiguration alloc] init];
    config.cameraDirection = [Tool safeIntForKey:@"camera-direction" defaultValue:1]; // 后置摄像头
    [self.agoraKit setCameraCapturerConfiguration:config];
    
    [self.agoraKit setLocalRenderMode:AgoraVideoRenderModeHidden mirror:mirrorIndex];
    self.mirrorButton.selected = mirrorIndex==2?YES:NO;
    [self.mirrorButton setImage:[UIImage imageNamed:self.mirrorButton.selected?@"mirror2":@"mirror1"] forState:UIControlStateNormal];
    
    // Set audio route to speaker
    [self.agoraKit setEnableSpeakerphone:YES];
//    self.isAgoraRtcBeauty = true;
//    BOOL isBeauty = false;
//    isBeauty = self.isAgoraRtcBeauty?true:false;
    if (!self.isAgoraRtcBeauty) {
        [Tool resetAllBeautifySettings];
    }
//    else{
//        int lear_result = [self.agoraKit enableExtensionWithVendor:@"agora_video_filters_clear_vision" extension:@"clear_vision" enabled:isBeauty sourceType:AgoraMediaSourceTypePrimaryCamera];
//         
//        if (lear_result != 0) {
//            NSLog(@"插件启用失败，错误码: %d", lear_result);
//            return;
//        }
//        
//        self.browStyleInt = [Tool safeIntForKey:@"browStyle" defaultValue:0];
//        self.lashStyleInt = [Tool safeIntForKey:@"lashStyle" defaultValue:0];
//        self.shadowStyleInt = [Tool safeIntForKey:@"shadowStyle" defaultValue:0];
//        self.pupilStyleInt = [Tool safeIntForKey:@"pupilStyle" defaultValue:0];
//        
//        
//        self.blushStyleInt = [Tool safeIntForKey:@"blushStyle" defaultValue:0];
//        self.blushColor = [Tool safeIntForKey:@"blushColor" defaultValue:0];
//        
//        self.lipStyleInt = [Tool safeIntForKey:@"lipStyle" defaultValue:0];
//        self.lipColor = [Tool safeIntForKey:@"lipColor" defaultValue:0];
//        
//        
//        //slider
//        self.browStrength = [Tool safeFloatForKey:@"browStrength" defaultValue:0.5];
//        self.lashStrength = [Tool safeFloatForKey:@"lashStrength" defaultValue:0.5];
//        self.shadowStrength = [Tool safeFloatForKey:@"shadowStrength" defaultValue:0.5];
//        self.pupilStrength = [Tool safeFloatForKey:@"pupilStrength" defaultValue:0.5];
//        self.blushStrength = [Tool safeFloatForKey:@"blushStrength" defaultValue:0.5];
//        self.lipStrength = [Tool safeFloatForKey:@"lipStrength" defaultValue:0.5];
//        self.lashColor  = [Tool safeIntForKey:@"lashColor" defaultValue:0];
//        self.browColor  = [Tool safeIntForKey:@"browColor" defaultValue:0];
//        
//        
//        self.makeupDict = @{
//            @"enable_mu": @YES, // 美妆开关
//            @"browStyle":@(self.browStyleInt),//眉毛类型 0 无, 1、2
//            @"browColor":@(self.browColor),//眉毛颜色 1 黑色，2，棕色
//            @"browStrength":@(self.browStrength),//取值范围为 [0.0, 1.0]
//
//            @"lashStyle":@(self.lashStyleInt),//眼睫毛 0 无, 1、2
//            @"lashColor":@(self.lashColor),//眼睫毛 颜色 1 黑色，2，棕色
//            @"lashStrength":@(self.lashStrength), //眼睫毛 取值范围为 [0.0, 1.0]
//
//            @"shadowStyle":@(self.shadowStyleInt),//眼影 0 无, 1、2
//            @"shadowStrength":@(self.shadowStrength),//取值范围为 [0.0, 1.0]
//
//            @"pupilStyle":@(self.pupilStyleInt),//瞳孔类型 0 无, 1、2
//            @"pupilStrength":@(self.pupilStrength),//取值范围为 [0.0, 1.0]。
//
//            @"blushStyle": @(self.blushStyleInt),  //腮红类型 0 无, 1、2
//            @"blushColor": @(self.blushColor),  // 腮红颜色 0 无, 1、2、3、4、5
//            @"blushStrength":@(self.blushStrength),//取值范围为 [0.0, 1.0]
//
//            @"lipStyle":@(self.lipStyleInt),//唇彩  0 无, 1、2
//            @"lipColor":@(self.lipColor),//颜色 0 无, 1、2、3、4、5
//            @"lipStrength":@(self.lipStrength),//取值范围为 [0.0, 1.0]
//            @"resPath":[Tool getMakeupResource],
//            
//        }.mutableCopy;
//
//        
//        NSError *error = nil;
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.makeupDict options:0 error:&error];
//        if (!jsonData || error) {
//            NSLog(@"JSON 转换失败: %@", error.localizedDescription);
//            return;
//        }
//        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//        if (!jsonString) {
//            NSLog(@"JSON 字符串转换失败");
//            return;
//        }
//       
//      
//                
//        [self.agoraKit setExtensionPropertyWithVendor:@"agora_video_filters_clear_vision"
//                                                   extension:@"clear_vision"
//                                                         key:@"makeup_options"
//                                                       value:jsonString
//                                                  sourceType:AgoraMediaSourceTypePrimaryCamera];
//    }

}

#pragma mark -  start joining channel 加入声网频道
- (void)joinChannelByToken{
    if (![Tool strIsNULL:self.corseInfoModel.user_id]) {
        // start joining channel
        AgoraRtcChannelMediaOptions *options = [[AgoraRtcChannelMediaOptions alloc] init];
        options.autoSubscribeAudio = YES;
        options.autoSubscribeVideo = YES;
        options.publishCameraTrack = YES;
        options.publishMicrophoneTrack = YES;
        options.clientRoleType = AgoraClientRoleBroadcaster;
        
        int result = [self.agoraKit joinChannelByToken:self.channelToken channelId:self.roomID uid:[self.corseInfoModel.user_id intValue] mediaOptions:options joinSuccess:nil];
        if (result != 0) {
        
            NSLog(@"joinChannel call failed: %d, please check your params", result);
        }else{
            NSLog(@"joinChannel call success");
            
            //开始直播
            [self startLiveAndStopWithAction:@"publish"];
        }
    }
   
}

// ViewController.m
// 监听 didJoinedOfUid 回调
// 远端用户加入频道时，会触发该回调
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didJoinedOfUid:(NSUInteger)uid elapsed:(NSInteger)elapsed {
//    AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
//    videoCanvas.uid = uid;
//    videoCanvas.renderMode = AgoraVideoRenderModeHidden;
//    videoCanvas.view = self.remoteView;
//    // 设置远端视图
//    [self.agoraKit setupRemoteVideo:videoCanvas];
}

#pragma mark - 网络判断
//* The SDK triggers this callback when it cannot connect to the server 10 seconds after calling
- (void)rtcEngineConnectionDidLost:(AgoraRtcEngineKit * _Nonnull)engine
{
    //10秒会调用
    NSLog(@"-------");
    self.offLoneSeconds = 10;
}


- (void)rtcEngine:(AgoraRtcEngineKit* _Nonnull)engine connectionChangedToState:(AgoraConnectionState)state reason:(AgoraConnectionChangedReason)reason
{
    if (state == AgoraConnectionStateConnecting) {
        NSLog(@"----连接房间中...---");
        [[ZXMessageCase shareInstace] showMessage:@"连接房间中..."];
    } else if (state == AgoraConnectionStateConnected) {
        NSLog(@"----房间已连接---");
        [self stopCountTimer];
        [[ZXMessageCase shareInstace] showMessage:@"房间已连接"];
        
        //bool
        if (!self.isFirstTimeLive) {
            [self startLiveAndStopWithAction:@"publish"];
        }
    }
   else if (state == AgoraConnectionStateReconnecting&&reason == AgoraConnectionChangedReasonLost) {
        NSLog(@"----网络丢失---");
       
       [self startCountSeconds];
       
    }
//   else if (state == AgoraConnectionChangedReasonRejoinSuccess || state == AgoraConnectionStateConnected){
//        NSLog(@"----重连成功---");
//        
//        [self stopCountTimer];
////        self.connectedCount++;
////        self.offLoneSeconds = 0;
////        if (self.connectedCount>3) {
////            
////            [self countRefresh];
////            
////        }else{
//            [[ZXMessageCase shareInstace] showMessage:@"重连房间成功"];
//            [self startLiveAndStopWithAction:@"publish"];
////        }
//       
//    }
}

- (void)startCountSeconds
{
    
    if (self.countTimer == nil) {
        
        self.countTimer = [NSTimer timerWithTimeInterval:50.0
                                                      target:self
                                                    selector:@selector(countRefresh)
                                                    userInfo:nil
                                                     repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)countRefresh
{
    [self stopCountTimer];
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前网络不稳定，请返回检查网络" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        
        [weakSelf quitRoom:YES];
    }];
    [alert addAction:okAction];
    // 弹出对话框
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf presentViewController:alert animated:true completion:NULL];
    });
}

- (void)stopCountTimer
{
    if (self.countTimer.isValid) {
        [self.countTimer invalidate];
        self.countTimer = nil;
    }
}

// 解锁时的回调方法
- (void)screenDidUnlock {
    NSLog(@"设备已解锁");
    if (self.isLive&&self.offLoneSeconds == 10) {
        self.offLoneSeconds = 0;
        [self startLiveAndStopWithAction:@"publish"];
    }
}

//根据场景需要，如结束通话、关闭 app 或 app 切换至后台时
- (void)leaveChannel {
    [self.agoraKit disableAudio];
    [self.agoraKit disableVideo];
    [self.agoraKit stopPreview];
    [self.agoraKit leaveChannel:nil];
    [AgoraRtcEngineKit destroy];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - 开始直播和暂停直播接口调用
- (void)startLiveAndStopWithAction:(NSString *)action{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/s_wang/notify/",HTTPSURL];
    NSDictionary *dic = @{@"action":action,
                          @"course_id":self.roomID};
    NSString *token = [NSString stringWithFormat:@"JWT %@",self.token];
    __weak typeof(self) weakSelf = self;
    [manager GET:urlString parameters:dic headers:@{@"authorization":token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        if ([responseObject[@"code"] intValue] == 200) {
            weakSelf.isFirstTimeLive = NO;
            if([action isEqualToString:@"publish"]){
                [weakSelf mergeTrack];
                [weakSelf startLiveParams];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error===%@",error);
    }];
}

#pragma mark - 结束直播
- (void)endLiveAction
{
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/system/end_course/%@/",HTTPSURL,self.roomID];
   
    NSString *token = [NSString stringWithFormat:@"JWT %@",self.token];
    [manager POST:urlString parameters:nil headers:@{@"authorization":token} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        if ([responseObject[@"code"] intValue] == 200) {
//            [weakSelf backAction];
//            [weakSelf leaveChannel];
//        }else{
////            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
//        }
        [weakSelf isEndLive];
        
//        if ([responseObject[@"code"] intValue] != 200) {
//            [[ZXMessageCase shareInstace] showMessage:responseObject[@"msg"]];
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error===%@",error);
    }];
}

- (BOOL)onCaptureVideoFrame:(AgoraOutputVideoFrame *)videoFrame sourceType:(AgoraVideoSourceType)sourceType {
    CVPixelBufferRef pixelBuffer = [self processFrame:videoFrame.pixelBuffer];
    videoFrame.pixelBuffer = pixelBuffer;
    return YES;
}

- (AgoraVideoFormat)getVideoPixelFormatPreference{
    return AgoraVideoFormatBGRA;
}
- (AgoraVideoFrameProcessMode)getVideoFrameProcessMode{
    return AgoraVideoFrameProcessModeReadWrite;
}
- (CVPixelBufferRef)processFrame:(CVPixelBufferRef)frame {
    [[FUTestRecorder shareRecorder] processFrameWithLog];
    if (![FUDemoManager shared].shouldRender) {
        return frame;
    }
    [[FUDemoManager shared] checkAITrackedResult];
    [FUDemoManager updateBeautyBlurEffect];
    FURenderInput *input = [[FURenderInput alloc] init];
    input.pixelBuffer = frame;
    //默认图片内部的人脸始终是朝上，旋转屏幕也无需修改该属性。
    input.renderConfig.imageOrientation = FUImageOrientationUP;
    //开启重力感应，内部会自动计算正确方向，设置fuSetDefaultRotationMode，无须外面设置
    input.renderConfig.gravityEnable = YES;
    input.renderConfig.stickerFlipH = _isFrontCamera;
    input.renderConfig.isFromFrontCamera = _isFrontCamera;
//    input.renderConfig.isFromMirroredCamera = YES;
    FURenderOutput *output = [[FURenderKit shareRenderKit] renderWithInput:input];
    return output.pixelBuffer;
}

#pragma mark - 开始直播的参数配置
-(void)startLiveParams{
    self.isRoomStateConnected = YES;
    self.seconds = 0;
    [self.timer invalidate];
    self.timer = nil;
    self.timeLabel.hidden = YES;
    self.timeCountLabel.hidden = YES;
    
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        weakSelf.seconds += 1;
        int minutes = weakSelf.seconds/60;
        int seconds = weakSelf.seconds%60;
        weakSelf.beginTimeLabel.text = [NSString stringWithFormat:@"直播中：%02d分%02d秒",minutes,seconds];
    }];
    self.beginTimeLabel.text = @"直播中：00分00秒";
    self.beginView.hidden = false;
    self.beginTimeLabel.hidden = false;
    self.closeButton.hidden = false;
    self.beginButton.hidden = true;
    self.isLive = true;
//    [self startFreshOnline];
}

- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine
    networkQuality:(NSUInteger)uid
    txQuality:(AgoraNetworkQuality)txQuality
    rxQuality:(AgoraNetworkQuality)rxQuality{
    NSString *netStr = @"";
    
    if (txQuality == AgoraNetworkQualityUnknown || txQuality == AgoraNetworkQualityDetecting) {
        netStr = @"qualityDetecting";
    }else if (txQuality == AgoraNetworkQualityExcellent)
    {
        netStr = @"qualityExcellent";
    }else if (txQuality == AgoraNetworkQualityGood)
    {
        netStr = @"qualityGood";
    }else if (txQuality == AgoraNetworkQualityPoor)
    {
        netStr = @"qualityPoor";
        [[ZXMessageCase shareInstace] showMessage:@"网络一般，建议切换到流畅模式" withColor:[UIColor redColor]];
    }else if (txQuality == AgoraNetworkQualityBad)
    {
        netStr = @"qualityBad";
        [[ZXMessageCase shareInstace] showMessage:@"网络较差，建议切换到流畅模式" withColor:[UIColor redColor]];
    }
    else if (txQuality == AgoraNetworkQualityVBad)
    {
        netStr = @"qualityVBad";
        [[ZXMessageCase shareInstace] showMessage:@"网络太差，建议更换网络" withColor:[UIColor grayColor]];
    }else if (txQuality == AgoraNetworkQualityDown)
    {
        netStr = @"qualityUnknown"; // 完全无法沟通。
        [[ZXMessageCase shareInstace] showMessage:@"网络无法直播，建议更换网络" withColor:[UIColor grayColor]];
        // 获取主队列（UI 操作需要在主线程执行）
        dispatch_queue_t mainQueue = dispatch_get_main_queue();

        // 设置延迟时间：3 秒
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC));

        // 使用 dispatch_after 延迟执行
        dispatch_after(delayTime, mainQueue, ^{
            [self quitRoom:YES];
        });
    }
    
    self.networkImg.image = [UIImage imageNamed:netStr];
}

- (void)rtcEngine:(AgoraRtcEngineKit * _Nonnull)engine reportRtcStats:(AgoraChannelStats * _Nonnull)stats
{
    self.networkView.hidden = NO;
    [self.bitrateBtn setTitle:[NSString stringWithFormat:@"码率：%lukbps",(unsigned long)stats.txKBitrate] forState:0];
}

#pragma mark -  Token 即将过期时回调
- (void)rtcEngine:(AgoraRtcEngineKit *)engine tokenPrivilegeWillExpire:(NSString *)token {
    [self getTokenWithCompletion:^(NSString *newToken) {
            if (newToken) {
                [engine renewToken:newToken];
            } else {
                NSLog(@"Failed to get new token");
            }
        }];
}

// 获取 Token 的方法
- (void)getTokenWithCompletion:(void (^)(NSString *token))completion {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userInfo = [defaults dictionaryForKey:@"userInfo"];
    NSDictionary *dict =  [[YouinRTCManager shardManager] readNSUserDefaults];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 30.0f;
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript",@"text/plain", nil];
    
    NSString *urlString = [NSString stringWithFormat:@"%@v1/course/system/s_wang_rtc_token/",HTTPSURL];
    NSDictionary *dic = @{@"channel_name":self.roomID};
    NSString *token = [NSString stringWithFormat:@"JWT %@",dict[@"token"]];
    [manager GET:urlString parameters:dic headers:@{@"authorization":token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            
            [[YouinRTCManager shardManager] loginIn:userInfo[@"username"] password:userInfo[@"password"] callback:^(NSDictionary *success, NSError * _Nullable error) {
                NSString *channelToken = responseObject[@"result"][@"token"];
                completion(channelToken);
            }];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error===%@",error);
        completion(nil);
    }];
    
}

- (void)dealloc
{
    NSLog(@"dealloc-:%@",[self class]);
    [FUDemoManager destory];
}
@end
